How do I implement swiping between tabs on Android?

NOTE: This is an excerpt from the Android Training class Implementing Effective Navigation.


To implement this (in Android 3.0 or above), you can use a ViewPager in conjunction with the ActionBar tabs API.

Upon observing the current page changing, select the corresponding tab. You can set up this behavior using an ViewPager.OnPageChangeListener in your activity’s onCreate() method:

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    mViewPager.setOnPageChangeListener(
            new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    // When swiping between pages, select the
                    // corresponding tab.
                    getActionBar().setSelectedNavigationItem(position);
                }
            });
    ...
}

And upon selecting a tab, switch to the corresponding page in the ViewPager. To do this, add an ActionBar.TabListener to your tab when creating it using the newTab() method:

actionBar.newTab()
        ...
        .setTabListener(new ActionBar.TabListener() {
            public void onTabSelected(ActionBar.Tab tab,
                    FragmentTransaction ft) {
                // When the tab is selected, switch to the
                // corresponding page in the ViewPager.
                mViewPager.setCurrentItem(tab.getPosition());
            }
            ...
        }));

Leave a Comment