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!!!

1 comment:

  1. I am curious to find out what blog platform you are using? I’m having some small security problems with my latest website and I would like to find something more secure. Do you have any solutions? free courses to learn kotlin