目录
一、前言
所使用到的控件如下:
com.google.android.material.tabs.TabLayout
com.google.android.material.tabs.TabItem
androidx.viewpager2.widget.ViewPager2
ViewPager2本质上是一个RecyclerView,只是被重新封装了,所以ViewPager2可以做一些很厉害的效果。
二、问题
TabLayout与ViewPager2进行联合使用,做一个关联滑动切换页面的效果时,明明在TabLayout里添加了TabItem,并且设置了文字。但两者关联上之后,还是出现tab都不显示文字,只是可以点击的现象。
布局文件关键代码如下:
<com.google.android.material.tabs.TabLayout
android:id="@+id/home_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:theme="@style/Theme.AppCompat"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/home_title"
app:tabIndicatorFullWidth="false"
app:tabIndicatorHeight="0dp"
app:tabSelectedTextColor="@color/color_primary_text"
app:tabTextAppearance="@style/TabLayoutTextAppearance"
app:tabTextColor="@color/white">
<com.google.android.material.tabs.TabItem
android:id="@+id/home_tab_device"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/home_tab_device" />
<com.google.android.material.tabs.TabItem
android:id="@+id/home_tab_scene"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/home_tab_scene" />
<com.google.android.material.tabs.TabItem
android:id="@+id/home_tab_linkage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/home_tab_linkage" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/home_view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/home_tab_layout" />
Java关联代码实现
因为TabLayout里只有和ViewPager的进行相关关联的接口,此时要联合使用ViewPager2则需要使用到TabLayoutMediator对TabLayout与ViewPager2进行attach(其实TabLayout和ViewPager联合使用也会有本文描述的问题存在,后面有机会再写一篇文章:)
new TabLayoutMediator(homeTabLayout, homeViewPager, new
TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
}
}).attach();
此时TabLayout与ViewPager2已经关联成功,并且ViewPager2左右滑动,TabLayout也能响应。TabLayout点击,ViewPager2也能响应,只是TabLayout的item无文字显示,但点击有反馈效果。
三、源码分析
待后续空闲后补充
四、解决
1.方法一:直接在TabConfigurationStrategy的回调onConfigureTab里,重新设置Text
new TabLayoutMediator(homeTabLayout, homeViewPager, new
TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
tab.setText(titles.get(position));
}
}).attach();
2.方法二:在attach方法之后,重新对Tab设定Text值
homeTabLayout.getTabAt(0).setText(R.string.xxx);
3.其他解决方式:由于ViewPager2是个RecyclerView,从这入手,解决方式就可以发散了,如adapter处理等,待后续空闲后验证补充