且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Android 上实现选项卡之间的滑动?

更新时间:2022-04-11 07:55:35

注意:这是摘自 Android 培训实施有效导航.

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

要实现这一点(在 Android 3.0 或更高版本中),您可以使用 ViewPagerActionBar 选项卡 API 结合使用.

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

观察当前页面变化后,选择相应的标签.您可以使用 ViewPager.OnPageChangeListener 在活动的onCreate() 方法:

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);
                }
            });
    ...
}

在选择一个标签后,切换到 ViewPager中的相应页面>.为此,请在使用 ActionBar.TabListener 创建标签时将code>newTab() 方法:

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());
            }
            ...
        }));