How to use TabLayout with ViewPager2 in Android

前端 未结 7 1740
春和景丽
春和景丽 2020-12-29 18:24

I want to use com.google.android.material.tabs.TabLayout component with Android\'s new ViewPager implementation androidx.viewpager2.widget.Vi

7条回答
  •  时光取名叫无心
    2020-12-29 19:07

    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.

    It's code will look like this in kotlin

    TabLayoutMediator(tabLayout, viewPager) { tab, position ->
      tab.text = tabTitles[position]
      viewPager.setCurrentItem(tab.position, true)
    }.attach()
    

提交回复
热议问题