How to use TabLayout with ViewPager2 in Android

前端 未结 7 1739
春和景丽
春和景丽 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 18:58

    You can use Kotlin extension function:

    fun TabLayout.setupWithViewPager(viewPager: ViewPager2, labels: List) {
    
        if (labels.size != viewPager.adapter?.itemCount)
            throw Exception("The size of list and the tab count should be equal!")
    
        TabLayoutMediator(this, viewPager,
            TabLayoutMediator.TabConfigurationStrategy { tab, position ->
                tab.text = labels[position]
            }).attach()
    }
    

    And call it:

     tabLayout.setupWithViewPager(viewPager, listOf("Tab A", "Tab B"))
    

提交回复
热议问题