如何在 Android 中将 TabLayout 与 ViewPager2 一起使用 [英] How to use TabLayout with ViewPager2 in Android
问题描述
我想将 com.google.android.material.tabs.TabLayout
组件与 Android 的新 ViewPager
实现 androidx.viewpager2.widget.ViewPager2
一起使用代码>.但是,TabLayout
提供的 setupWithViewPager(..)
方法仅支持旧的 ViewPager
实现.有没有办法轻松地将 TabLayout
绑定到 ViewPager2
组件?
I want to use com.google.android.material.tabs.TabLayout
component with Android's new ViewPager
implementation androidx.viewpager2.widget.ViewPager2
. However, the setupWithViewPager(..)
method provided by TabLayout
supports only the old ViewPager
implementation. Is there a way to bind a TabLayout
to a ViewPager2
component easily?
推荐答案
你必须使用 this TabLayoutMediator
模仿 tabLayout.setupWithViewPager()
和使用 Tablayout
设置 ViewPager2
.否则,您将不得不编写自己的适配器来结合双方.
You have to use this TabLayoutMediator
that mimics tabLayout.setupWithViewPager()
and sets up the ViewPager2
with Tablayout
. Otherwise, you will have to write your own adapter that will combine both parties.
它的代码在 Kotlin 中看起来像这样
Its code will look like this in Kotlin
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = tabTitles[position]
}.attach()
这篇关于如何在 Android 中将 TabLayout 与 ViewPager2 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!