Fragment Tab

Same as the previous example, but each tab now invokes a Fragment instead of an Activity. The deprecated class TabActivity is no longer used. The tabs appear in the ActionBar. See Fragments and Action Bar.

At any time, there has to be a selected tab. When the first tab is created, it is therefore selected. The addTab method selects the third tab, unselecting the first one. When the app is launched, we see the following Toast messages:

  1. Selected Tab1Fragment
  2. Unselected Tab1Fragment
  3. Selected Tab3Fragment

“reselected” means you pressed the same tab twice in a row.

Source code in Tab.zip

Each Fragment has an onCreateView method.

  1. MyTabActivity.java
  2. Tab1Fragment.java
  3. Tab2Fragment.java
  4. Tab3Fragment.java
  5. main.xml: a TabHost containing a TabWidget and a FrameLayout. The id numbers (android.R.id.tabs) and (android.R.id.tabcontent) do not have plusses.
  6. ic_tab2.xml contains a State List: selected and unselected.
  7. ic_tab2_grey.png: selected, 32 × 32 pixels.
  8. ic_tab2_white.png: unselected.
  9. AndroidManifest.xml has four activity elements.

Tabs in ApiDemos/App/Action Bar/Action Bar Tabs

Same as the above example. Press the “Toggle tab mode” button first. The ActionBar holds tabs. Each tab holds a TabListener. Each TabListener holds a Fragment. Each Fragment holds a View.

  1. ActionBarTabs.java
  2. action_bar_tabs.xml
  3. action_bar_tab_content.xml

Tabs in ApiDemos/App/Fragment/Tabs

Retains fragment state of the non-visible tabs across Activity instances.

  1. FragmentTabs.java
  2. FragmentStack.java
  3. LoaderCursor.java
  4. LoaderCustom.java
  5. LoaderThrottle

Things to try

  1. A tab in an ActionBar looks ugly: all uppercase, no space between icon and text. Can you clean it up with setCustomView?