Tuesday, 21 May 2019

Kotlin for Android development essentials: TabLayout for ViewPager

In the previous blog post (link) I have shown you how to use ViewPager to change Fragment with swipe gesture. In this blog post, I will show you how to add tab layout to indicate which fragment is being shown.

You only need to make some small changes to three files.

Firstly, add the following line to the dependencies block of build.gradle.
implementation 'com.android.support:design:28.0.0'

Secondly, add the TabLayout to the ViewPager view in the layout file of main activity (activity_main.xml) like the following.

Finally, add the following function to the ViewPagerAdapter class in ViewPagerAdapter.kt.
override fun getPageTitle(position: Int): CharSequence? {
     return (position+1).toString()

That is all! Just compile and run our app with beautiful tab layout at the top!!!

No comments:

Post a Comment