Looking For Anything Specific?

[Tutorial] ViewPage2 With Fragments And Tab Layout In Android Kotlin Sample GitHub Code

ViewPager2 in android is the best-known way to create slide between screen like UX, in our recent article about ViewPager2 we have shared a little knowledge on how you can create ViewPager2 in android with kotlin, Since its an updated version of the old ViewPager in android it uses the famous RecyclerView Adapter to create and show the pages in a carousel to slide between screens. In this tutorial, we are going to give you an example of how to use fragments in viewpager2 with tab layout. If you want to know more about the android fragment you follow the below link

Android Fragment Basics In Kotlin

ViewPager2 With Fragments:

ViewPager2 is a well know UI widget in android for creating carousels, we learned a bit about them in the previous article on How to create a viewpager2 in android with kotlin, whereas we only discussed a single layout screen to show an array of data, But ViewPager2 is not limited to that the use cases and it has a lot of capabilities and our requirements also change to compete with modern applications and to give the user a better experience we need to do more than just using a single layout to show UI, So let's say you have three different screens each with its own design and functionality, and if you wanted to give the user quick navigation between those three screens and a swipe to navigate through, then you definitely need to use ViewPager2, we know that fragments are like "sub-activity" we can use multiple fragments in a single activity each has its own set of functionality.

illustration of android viewpager2 fragment using kotlin tutorial example code

So to put things in perspective, let's look at an example, So we are on earth and here we have three-time frames namely Morning, Evening, and Night I accept we have more than that but let's not complicate things just keep it simple for now, so consider Earth is an activity which can hold three fragments which are the time frames which we mentioned earlier and each time frame has its own set of characteristics and functions, simple as it is and this is what we are going to achieve through our code, we create the earth and add three-time frames. To get a better understanding of what we are going to do in this example to create viewpager2 with fragments, look at the sample output at the end of this article

Create ViewPager2 In Activity With TabLayout:

We start off by creating our android activity, if you want to recap on android activity peek a quick look at this article, Now that you have your activity we add the two widgets a ViewPager2 and TabLayout

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </androidx.viewpager2.widget.ViewPager2>

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
</androidx.constraintlayout.widget.ConstraintLayout>

This is our constraint layout where we made a simple design with only two mentioned widgets, if you are familiar with ViewPager you might add the tab layout inside the ViewPager widget but notice that in ViewPager2 you cannot add any views inside as that might crash your application by throwing an Exception stating ViewPager2 should not have any child, so we need to add both the widgets separately.

MainActivity.kt


val tabTitles = arrayOf("Morning","Evening","Night")
        
        val viewPager = findViewById<ViewPager2>(R.id.viewPager)
        viewPager.adapter = ViewPagerFragmentAdapter(this,tabTitles)

        val tabLayout = findViewById<TabLayout>(R.id.tabLayout)
        TabLayoutMediator(tabLayout,viewPager){tab, position ->
            tab.text = tabTitles[position]
        }.attach()

 Now move on to your activity, in here we add an array as mentioned before we add three time frames as we are going to have three fragments on the earth(our activity).

How To Add TabLayout To ViewPager2 In Kotlin:

The big question, how are we going to connect both viewpager2 and tab layout together to make it work, actually that is simple because Thanks to The Android Developers they have provided us a class called TabLayoutMediator, this is a mediator which will connect the TabLayout with the ViewPager and handle the synchronization of changing the tabs based on the ViewPager2's position. 

android tablayout added to a viewpager2 using kotlin
Android TabLayout with ViewPager2

Create a new TabLayoutMediator with two parameters which are the TabLayout and the ViewPager2 after adding these two parameters you have a configuration callback in which we will configure our tabs like setting the tab text and another styling if necessary, in one of our articles we shared how to show circle indicators in ViewPager2, and finally, we need to call attach() function in order for our TabLayout to link with the ViewPager2.

Add FragmentStateAdapter To ViewPager2 :

In the above code, in our activity code part, we set the adapter to the view pager for which we provided a ViewPagerFragmentAdapter which is a user-created adapter class, we use this class instead of a RecyclerViewAdapter. 

Create a new class and name it "ViewPagerFragmentAdapter", this is the class that is going to handle the main part of our code on how to add the fragments to the ViewPager2, we need to extend this class with FragmentStateAdapter you can learn more about FragmentStateAdapter here this class itself also extends RecyclerView Adapter which I found is very interesting, Well that's an article for another day, our FragmentStateAdapter has different constructors we use the one with Activity since our view pager is in the activity.

Then once created that class we need to override two functions one to define how many fragments we are going to need and one to create the fragments, you can refer to the below code on the implementation

ViewPagerFragmentAdapter.kt

  class ViewPagerFragmentAdapter(appCompatActivity: AppCompatActivity, private val tabTitles:Array<String>) :
    FragmentStateAdapter(appCompatActivity) {


    override fun getItemCount(): Int =  tabTitles.size

    override fun createFragment(position: Int): Fragment {
        return when(position){
            0 ->{
                MorningFragment().let {
                    val bundle = Bundle()
                    bundle.putString("PAGE_TITLE",tabTitles[position])
                    it.arguments = bundle
                    return it
                }
            }
            1 -> {
                EveningFragment().apply {
                    val bundle = Bundle()
                    bundle.putString("PAGE_TITLE",tabTitles[position])
                    arguments = bundle
                }
            }
            else -> {
                NightFragment().apply {
                    val bundle = Bundle()
                    bundle.putString("PAGE_TITLE",tabTitles[position])
                    arguments = bundle
                }
            }
        }
    }

}
  
Above is the complete adapter we used to create a view pager with fragments, To create this adapter we need to pass two parameters one is the Activity reference which is required by FragmentStateAdapter and additionally we pass an array, that array will be used to set the number of fragments we wanted to create and we will put the page's title as the elements in the array.


Here we are overriding getItemCount method to define how many fragments we need to create and in the createFragment function we will create those fragments which will give us the position of the ViewPager2's screen which is being displayed to the user, so based on that position we will create a new fragment and return it, additionally to demonstrate on how to send data to the fragments in the ViewPager2 we created a new bundle and used putString to add a new string and supplied that bundle to the arguments which we can access in the fragment, You can learn more about How to Pass Data Between Fragments in this article.

Finally, once we created the Adapter we set the adapter to our ViewPager2 and it will show them as a sliding screen,

demonstrating final output of android viewpager2 with fragments and tab layout developed using kotlin with sample code
Android ViewPager2 Fragment With TabLayout


Conclusion:

As mentioned earlier, we created An Activity (Earth) which will have three fragments (Morning, Evening, and Night), for that we use FragmentStateAdapter, and we attach the ViewPager2 to a TabLayout using a TabLayoutMediator which will handle the functionality to show the selected fragments name highlighted. Like Always I have shared the project code in GitHub, this code is shared on the same project under a different branch, If you like this project give it a star on GitHub it will help others find it easily. 

You Might Be Interested:

!!!Thanks For Reading Sharing Is Caring!!!

Don't Forget To Like and Follow Me

keywords:
ViewPager with fragments example in Android
ViewPager2 FragmentStateAdapter example
viewpager2 with tablayout android kotlin example

Post a Comment

0 Comments