Reputation: 29745
One of the key design recommendations in Android 4.0 for tabs is to allow swiping between them where appropriate. This behavior enables users to swipe horizontally across the selected tab's contents to navigate to adjacent tabs, without needed to directly interact with the tabs themselves.
How can this be implemented?
Upvotes: 26
Views: 25215
Reputation: 4777
If you are targeting APIs below Android 3.0, you cannot use Roman's solution above.
I wrote a blog post here about how to accomplish the same thing with ActionBarSherlock if anyone is interested.
Upvotes: 12
Reputation: 29745
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());
}
...
}));
Upvotes: 34