Kotlin Android TabLayout with ViewPager
Android TabLayout is a Layout which is used to build horizontal tabs. The tabs for the TabLayout is created using the newTab() method. To display this tab over the layout, we need to add this tab using addTab(Tab) method.
Using the methods setText(int) and setIcon(int) we set the title and icon of TabLayout respectively.
We can also integrate the ViewPager with TabLayout. ViewPager provides smooth sliding of tabs over layout.
Kotlin Android TabLayout with ViewPager Example
In this example, we will create a TabLayout with ViewPager.
build.gradel
Add the following dependency in the build.gradle file.
activity_main.xml
Add the TabLayout and ViewPager in the activity_main.xml file.
strings.xml
colors.xml
MainActivity.kt
Add the following code in MainActivity.kt class. In this class, the new tab is created using tabLayout!!.newTab() method and this tab is added over TabLayout using tabLayout!!.addTab(Tab).
Call the addOnPageChangeListener() listener of ViewPager to load the tabs on page change.
MyAdapter.kt
Create an adapter class MyAdapter.kt and extends FragmentPagerAdapter() class and returns the Fragment. Add this adapter class over ViewPager.
Create a fragment as New -> Fragment -> Fragment (Blank).
fragment_home.xml
HomeFragment.kt
fragment_sport.xml
SportFragment.kt
fragment_movie.xml
MovieFragment.kt
Output: