Android tab control: the new way

29 Jul

Android SDK now deprecated TabActivity, as you can see the strike through symbol in previous post. Using the new Android SDK, it is preferred to use Fragment instead, and it is also pretty easy.

  • Create a new android project in Eclipse
  • Create two (as many as you like) activities Fragments in Eclipse:
    > Right click the Package Exporer, New > Other, or press Ctrl + N;
    Select Android layout, name it fragment_tabpage1 and fragment_tabpage2


image  image

Fragment 1 and Fragment 2.

Also remember to add two Java class for these two layout, and inflate the layout in OnCreateView() override:


  • Create a new Activity as the NewTabActivity MainActivity, make sure it extends from Activity, instead of TabActivity. And one of the example xml file might be as follows, where we define a container to host different tabpages (fragments):


  • In NewTabActivity onCreate() function, add below code:


  • Simple? Yes, but if you build the app, you will see that it crashes! Yes, crash!
  • The reason is that for each Tab, there must be a TabListener  associated, and if not, it will crash. To do so, add below code:


  • Now the good thing is that we have a chance to specify which Fragments we want to add to the tabbed containers, but the cumbersome issue is that we have to provide a new class implementing the TabListener interface!
  • All right, let’s be lazy and copy a TabListener file from the web, and if you like, you can code yourself as well, but let’s be lazy!
  • But don’t be too lazy, replace the tab host container as shown in step 3, to make sure where we want to place each tab page, and the code should be like this:


Build and run, yeah! We can use fragment to implement Android Tabs! 

 image  image

Leave a comment

Posted by on July 29, 2013 in Android, Programming


Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: