Android development blog
Tutorials about Android dev topics

Android Action Bar (ActionBar) Tab navigation

Topics covered

Android Action bar (actionbar)

Android tab navigation

Tab with fragments

Action bar (ActionBar) was introduced from API level 11. In this post I will explain how to create actionbar tab navigation using fragments. The final result is shown below where user can move between tabs.
android_actionbar_tab

Creating the Action bar (ActionBar) with tab navigation

The first step is getting the actionbar reference and add the tab to it:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);   
    ActionBar bar = getActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    
    for (int i=1; i <= 3; i++) {
        Tab tab = bar.newTab();
        tab.setText("Tab " + i);
        tab.setTabListener(this);
        bar.addTab(tab);
        
    }
}

Notice that first of all we don’t use any “main” layout. Second at line 3 we get the reference to the action bar simply using the method getActionBar. At line 4 we set the navigation mode in our case NAVIGATION_MODE_TABS. There three different navigation type supported:
  • Navigation mode list
  • Navigation mode standard
  • Navigation mode tabs

After these steps we have to create our tabs and add it to the action bar. In our example we create three different tabs. What we want is when user touches one of the tab the UI content changes. To achieve it we need two things:
  • Fragment that fills the UI when user changes the tab according to the tab selected
  • A listener that gets notification when user interacts with the tabs

Tab Fragment

In our example, fragment will be very simple, it just shows a text in the middle of the screen. The layout looks like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    
    <TextView android:id="@+id/msg"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerInParent="true"
            />

</RelativeLayout>

While the fragment source code is very simple:
public void onCreate(Bundle savedInstanceState) {        
    super.onCreate(savedInstanceState);
    Bundle data = getArguments();
    index = data.getInt("idx");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    
    View v = inflater.inflate(R.layout.fragment, null);
    TextView tv = (TextView) v.findViewById(R.id.msg);
    tv.setText("Fragment " + (index + 1));
    
    return v;
    
}

Just notice that we pass the fragment index using arguments bundle (line 2,3).Now we have our fragment we have simply to implement the listener.

Tab listener

We can make our Activity implements the listener so that when user selects a tab we show the relative fragment.
public class MainActivity extends Activity implements TabListener {
   List<Fragment> fragList = new ArrayList<Fragment>();
   Fragment f = null;   // Thx to Andre Krause for his support!
   TabFragment tf = null;

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
//        Fragment f = null;
//        TabFragment tf = null;
        
        if (fragList.size() > tab.getPosition())
                fragList.get(tab.getPosition());
        
        if (f == null) {
            tf = new TabFragment();
            Bundle data = new Bundle();
            data.putInt("idx",  tab.getPosition());
            tf.setArguments(data);
            fragList.add(tf);
        }
        else
            tf = (TabFragment) f;
        
        ft.replace(android.R.id.content, tf);
        
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        if (fragList.size() > tab.getPosition()) {
            ft.remove(fragList.get(tab.getPosition()));
        }
        
    }
}
TabListener has several methods we have to override. The most important is onTabSelected that is called when user selects a tab. In this method first we check if we have our fragment in the fragment list (line 9-10), if so we reuse it and show the fragment (see line 20). If not, we create our fragment line (12-18) and add it to our fragment list. At the end (line 22), we simply replace the UI content (android.R.id.content) with the right fragment. The result is shown below:
android_actionbar_tab2android_actionbar_tab3
Source code available @github


16 comments:

  1. As per the design guidelines (http://developer.android.com/design/patterns/swipe-views.html#between-tabs), you should really enable swiping between the action bar tabs by using a ViewPager. There's a good tutorial in the training section which explains how to do it: http://developer.android.com/training/implementing-navigation/lateral.html

    ReplyDelete
  2. survivingwithandroidJuly 18, 2013 at 12:38 PM

    Can you explain?

    ReplyDelete
  3. Simon MayerhoferJuly 21, 2013 at 3:41 PM

    Whats the class of the object fragList refers to?

    ReplyDelete
  4. survivingwithandroidJuly 22, 2013 at 11:54 AM

    I've edited the source code so it is more clear. Anyway fraglist is defined as

    List fragList = new ArrayList();

    Thx for your comment

    ReplyDelete
  5. im getting an error:

    "The method remove(Fragment) in the type FragmentTransaction is not applicable for the arguments (Fragment)"

    this error is at lines:

    ft.replace(android.R.id.content, tf);

    ft.remove(fragList.get(tab.getPosition()));



    Also what data type is "index"

    ReplyDelete
  6. survivingwithandroidAugust 19, 2013 at 10:49 PM

    I've added the full source code at github. Look at the link in the post. You can download all the source code. Thx

    ReplyDelete
  7. The source code still gives the error, what's the solution?

    ReplyDelete
  8. hey if i want to add a swipe gesture to switch between different tabs how would i do that??

    ReplyDelete
  9. what is "fragList.get(tab.getPosition());" in line 10 use for?

    and "f" in line is always null, so u always create a new TabFragment and not reuse like u say

    i change the code to "f =fragList.get(tab.getPosition());" in line 10

    but it will be an error because fragList position not always same to tab position
    example when u click tab 3 first when the app loaded

    ReplyDelete
  10. Is there any way to easily implement swiping between these tabs?


    Apologies, I'm an android noob, just trying to work it out.


    Also, how do I define each of these fragments, so that I can have different content in each? I understand right now it is a loop to generate example fragments.


    Thanks!

    ReplyDelete
  11. you can use ViewPager from android support v4 too do that, i really know if Tab can do that or not


    for different content each Fragment, just create some class that extends Fragment, each class can have a different view and content

    ReplyDelete
  12. *i dont really know

    ReplyDelete
  13. Very useful! Working. Thanks

    ReplyDelete
  14. Hello, thank you for this, but I now have a problem:
    I don't know how I can stay on the selected Tab when I come back (by a back button) after I started another activity in this view? You understand what I want? I get on the third tab, click on something, a new activity starts, and I want to come back an the third tab by a button. The best would be that the tabbar still stay there so I also could select from this the other tabs.

    ReplyDelete
  15. Hello Fransceo,


    Thank you for the tutorial. I wanted to ask how we can go from tab 1 to tab 2 by clicking on a button on tab1 layout.?
    Thanks,
    Sushant

    ReplyDelete

Related Posts with Thumbnails