Kotlin : Android’s future is here – Part 7

Overview

Tab Layout

This blog is about implementing tab layout in Android using Kotlin.

Tab Layout with view pager

Including tab layout & view pager in xml

Create the fragments that you want to display inside the view pager when tab is selected

Here, we will display different colored background for each fragment in view pager.
I’ll show one fragment here, for instance.

XML file:-

Kotlin file:-

Implementing FragmentStatePager Adapter

Here, I have used 2 arrayLists; one for storing fragments and 1 for storing names of tabs.

To display names of tabs on tab selection, getPageTitle( ) method is overridden in adapter and it returns name of the tab at selected position.

To display fragment on tab selection, getItem( ) method is overridden in adapter which returns the fragment at selected position.

Code in MainActivity.kt

Tab Layout without view pager

Including tab layout & a frame layout in xml

Create the fragments that you want to display when tab is selected

Here, we will display different colored background for each fragment.
I’ll show one fragment here, for instance.

XML file:-

Kotlin file:-

Code in MainActivity.kt

First, we have to design the tab layout before loading fragments in frame layout i.e. setting icon and text for each tab.

Then, I have loaded 1st fragment in the frame layout.

Finally, I have used addOnTabSelectedListener( ) to detect the selected tab and then on selection of the tab, I have loaded the respective fragment in the frame.

Conclusion

Tab layouts are in fashion now-a-days. We see them in facebook, whatsapp and other such giant apps. Hence, it is a good idea to learn to code tab layouts in Kotlin because it will be a must requirement in future projects.

mm

Sumeet Rukeja Android Developer

I am an Android Developer at Yudiz Solutions Pvt. Ltd. - a leading Mobile App Development Company. I am passionate about developing android apps and to learn more and more about the deep sea of Android.

Comments are closed.

Top