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)
activitiesFragments in Eclipse:
> Right click the Package Exporer, New > Other, or press Ctrl + N;
> Select Android layout, name it fragment_tabpage1 and fragment_tabpage2
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!