Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use TabLayout with ViewPager2 in Android

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?

like image 648
Ugurcan Yildirim Avatar asked Mar 27 '19 07:03

Ugurcan Yildirim


People also ask

How do I use TabLayout with ViewPager2 on Android?

Open the MainActivity class. Firstly, initialize ViewPager2 and TabLayout then set the adapter on ViewPager2. Then, create a TabLayoutMediator to link the TabLayout to the ViewPager2, and attach it.

How do I use TabLayout on Android?

This example demonstrates how do I create a Tab Layout in android app. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 3 − Add the following code to res/layout/activity_main. xml.


1 Answers

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.

Its code will look like this in Kotlin

TabLayoutMediator(tabLayout, viewPager) { tab, position ->   tab.text = tabTitles[position] }.attach() 
like image 117
Nikola Despotoski Avatar answered Sep 23 '22 18:09

Nikola Despotoski