Kotlin Android TabLayout with ViewPagerAndroid 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 ExampleIn this example, we will create a TabLayout with ViewPager. build.gradelAdd the following dependency in the build.gradle file. activity_main.xmlAdd the TabLayout and ViewPager in the activity_main.xml file. strings.xmlcolors.xmlMainActivity.ktAdd 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.ktCreate 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.xmlHomeFragment.ktfragment_sport.xmlSportFragment.ktfragment_movie.xmlMovieFragment.ktOutput:
Next Topic#
|