How to use ViewPager2 with TabLayout in Android?

Emine İNAN
Busoft
Published in
2 min readMay 14, 2021

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.

activity_main.xml

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.

CatFragment.kt
fragment_cat.xml

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.
ViewPagerAdapter.kt

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.

MainActivity.kt

Step 7

Run your application.

--

--

Emine İNAN
Busoft
Writer for

Android Developer by day, Android Developer by night. @Huawei