Android TabLayout
TabLayout is used to implement horizontal tabs. TabLayout is released by Android after the deprecation of ActionBar.TabListener (API level 21).
TabLayout is introduced in design support library to implement tabs.
Tabs are created using newTab() method of TabLayout class. The title and icon of Tabs are set through setText(int) and setIcon(int) methods of TabListener interface respectively. Tabs of layout are attached over TabLayout using the method addTab(Tab) method.
We can also add tab item to TabLayout using TabItem of android design widget.
Example of TabLayout using ViewPager
Let’s create an example of TabLayout using ViewPager and Fragment.
File: activity.xml
Create an activity.xml file with TabLayout and ViewPager view components.
File: build.gradle
Now gave the dependency library of TabLayout in build.gradle file.
File: MainActivity.java
In this file, we implement two additional listener addOnPageChangeListener(listener) of ViewPager which makes slides the different fragments of tabs and addOnTabSelectedListener(listener) of TabLayout which select the current tab on tab selection.
File: MyAdapter.java
Now create different fragment files for all different tabs.
File: HomeFragment.java
File: fragment_home.xml
File: SportFragment.java
File: fragment_sport.xml
File: MovieFragment.java
File: fragment_movie.xml
File: strings.xml
Output