How to use TabLayout with ViewPager2 in Android

Ugurcan Yildirim picture Ugurcan Yildirim · Mar 27, 2019 · Viewed 40.4k times · Source

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?

Answer

Nikola Despotoski picture Nikola Despotoski · Mar 29, 2019

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()