How to use ViewPager2 with TabLayout in Android?
In this article, we will learn how to use ViewPager2 with TabLayout in an app. TabLayout is used to display tabs horizontally, while ViewPager2 is used to creating views in a swipeable format.
Let’s start to use ViewPager2 with TabLayout in an example.
Step 1
Create a new project in Android Studio.
Step 2
Remove the ActionBar because we will use the Toolbar instead. So go to res/values/themes.xml and change the app theme as NoActionBar.
Step 3
Open the activity_main.xml and add ToolBar, TabLayout and ViewPager2.
Step 4
Create one Fragment for each tab. In this project I will be displaying three tabs so I need to create three Fragments. I will show a different animal image under each tab, so I add one ImageView to the layout file of these Fragments.
Note: I am not adding the remaining two Fragments code because it is very similar to this one, you can find them in the source code.
Step 5
Create a class extending from FragmentStateAdapter to swipe Fragments, then override getItemCount() and createFragment(position: Int) methods.
- getItemCount(): This method returns the total number of items in the Adapter.
- createFragment(position: Int): This method returns a Fragment instance for the given position.
Step 6
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.
Step 7
Run your application.
That’s it for this article, thanks for reading.
For the complete code: