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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10134332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:36:42  来源:igfitidea点击:

How do I implement swiping between tabs on Android?

androidtabsandroid-viewpager

提问by Roman Nurik

One of the key design recommendations in Android 4.0 for tabs is to allow swipingbetween 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.

Android 4.0 中标签的关键设计建议之一是允许在适当的情况下在它们之间滑动。此行为使用户能够在所选选项卡的内容上水平滑动以导航到相邻的选项卡,而无需直接与选项卡本身进行交互。

How can this be implemented?

如何实施?

回答by Roman Nurik

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

注意:这是Android 培训课程实施有效导航的摘录。



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

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

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

观察当前页面的变化,选择相应的选项卡。您可以在活动的方法中使用ViewPager.OnPageChangeListener设置此行为onCreate()

@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.TabListenerto your tab when creating it using the newTab()method:

并在选择一个选项卡后,切换到ViewPager 中的相应页面。为此,请在使用以下方法创建选项卡时将ActionBar.TabListener添加到您的选项卡newTab()

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

回答by JesperB

If you are targeting APIs below Android 3.0, you cannot use Roman's solution above.

如果您的目标 API 低于 Android 3.0,则不能使用上述 Roman 的解决方案。

I wrote a blog post hereabout how to accomplish the same thing with ActionBarSherlock if anyone is interested.

如果有人感兴趣,我在这里写了一篇关于如何使用 ActionBarSherlock 完成同样事情的博客文章