使用TabItem时如何将TabLayout与ViewPager同步 [英] How sync TabLayout with ViewPager when using TabItem

查看:417
本文介绍了使用TabItem时如何将TabLayout与ViewPager同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将TabLayoutTabItem结合使用,并使用以下代码:

I want to use TabLayout with TabItem with following code:

  <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/color_primary"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/white"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/white"
        app:tabTextColor="@color/gray_light">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:icon="@drawable/ic_language" />


        <!-- other tabs ... -->


    </android.support.design.widget.TabLayout>

这是向我显示正确的图标,如下所示:

And this is show me Icons correctly like this:

但是问题是当我想将我的TabLayout添加到ViewPager中时,使用以下代码,它们全部存在并且可以单击但消失了.我错过了什么吗?

But the problem is when I want to add my TabLayout to ViewPager, with following code, all of them exist and clickable but disappear. Did I miss something?

 MyPagerAdapter adapter = new MyPagerAdapter(getFragmentManager());
 pager.setAdapter(adapter);

 tabLayout.setupWithViewPager(pager);

这是结果:

推荐答案

tabLayout.setupWithViewPager(pager)要做的是在视图分页器的适配器上调用getPageTitle()并使用返回的字符串创建选项卡.我建议不要调用setupWithViewPager().然后,您需要做两件事:

What tabLayout.setupWithViewPager(pager) is going to do is call getPageTitle() on the view pager's adapter and create tabs with the strings that are returned. I would recommend not calling setupWithViewPager(). Then you will need to do two things:

  • 使用OnPageChangeListener实现调用viewPager.addOnPageChangeListener,该实现将根据所选页面选择选项卡.

  • Call viewPager.addOnPageChangeListener with an OnPageChangeListener implementation that will select the tab based on the selected page.

使用OnTabSelectedListener实现调用tabLayout.setOnTabSelectedListener,该实现将使用选定的标签号调用viewPager.setCurrentPage().

Call tabLayout.setOnTabSelectedListener with an OnTabSelectedListener implementation that will call viewPager.setCurrentPage() with the selected tab number.

只需确保您的PagerAdapter计数与TabLayout中的选项卡数匹配.

Just make sure your PagerAdapter count matches the number of tabs in your TabLayout.

这篇关于使用TabItem时如何将TabLayout与ViewPager同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆