[英]How can I make the Tablayout also scrollable
I wrote this code,but the tablayout is not scrollable,instead all the tabs shifting towards left, but view pager is working properly.我写了这段代码,但选项卡布局不可滚动,而是所有选项卡都向左移动,但视图寻呼机工作正常。
When I scroll viewpager,tab items are moving,I want the tabitems should be scrollable with tablayout.当我滚动 viewpager 时,标签项正在移动,我希望 tabitems 应该可以使用 tablayout 滚动。
<com.google.android.material.tabs.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorblue"
app:tabGravity="center"
android:layout_gravity="center_horizontal"
app:tabMode="scrollable"
app:tabIndicatorColor="@color/colorgeydark"
app:tabSelectedTextColor="@color/colorwhite"
app:tabTextColor="@color/colorgeydark"
android:layout_marginTop="5.5dp"
app:tabBackground="@android:color/transparent"
app:tabContentStart="0dp"
/>
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/tablayout"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
you need to add a TabLayout.TabLayoutOnPageChangeListener to the viewPager and a TabLayout.OnTabSelectedListener to the tabLayout您需要将 TabLayout.TabLayoutOnPageChangeListener 添加到 viewPager 并将 TabLayout.OnTabSelectedListener 添加到 tabLayout
//kotlin sample //kotlin 示例
viewPager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabLayout))
tabLayout.addOnTabSelectedListener(TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
//here the view pager will change
viewPager.setCurrentItem(tab.position, false)
}
override fun onTabUnselected(tab: TabLayout.Tab) {
}
override fun onTabReselected(tab: TabLayout.Tab) {
}
})
app:tabGravity="center"
only works with app:tabMode="fixed"
So if you want to make tab scrollable and center aligned then you have to set tab mode to fixed else tab will be left aligned. app:tabGravity="center"
仅适用于app:tabMode="fixed"
因此,如果您想让标签可滚动并居中对齐,则必须将标签模式设置为固定,否则标签将左对齐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.