问题描述
我想将TabLayout
与TabItem
结合使用,并使用以下代码:
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 anOnPageChangeListener
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同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!