If you are here that means you already know what you want. So, in this post we are going to learn about how to create tabs using the new ViewPager2 library. Let’s begin
First you have to create a simple project, and I hope you have it set-up at this point. Let me show you the example project structure which we will follow.
NOTE: I have intentionally left out the view mapping part in this post.
As you can see in the image below you can see four classes in total,but what are they ? There are exactly 2 fragments viz. SimpleItemFragment
and Vp2Fragment
and we have an adapter Vp2Adapter
with a MainActivity
.
Next up, we are going to prepare our layouts, which right here is nothing fancy. It is just painfully minimal for the sake of mere demonstration.
The layout of our MainActivity
is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Code language: HTML, XML (xml)
And SimpleItemFragment
‘s layout as
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".vp2.SimpleItemFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/app_name"
android:textAlignment="center" />
</RelativeLayout>
Code language: HTML, XML (xml)
Finally, the layout for Vp2Fragment is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:orientation="vertical"
tools:context=".vp2.Vp2Fragment">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/tab_layout" />
</RelativeLayout>
Code language: HTML, XML (xml)
Here in the code above we have TabLayout
which belongs to com.google.android.material.tabs
which you might have not already in your project. Let us see how we can include our dependencies.
Also Read: How to get current GPS location in Android
TECHENUM
INCLUDING THE ViewPager2 DEPENDENCY
There is not really much to do when it comes to including the dependency. Just add the code below in dependencies { }
block of app > build.gradle
and you’re all set after a gradle sync.
implementation 'androidx.viewpager2:viewpager2:1.0.0'
implementation 'com.google.android.material:material:1.2.0'
Code language: Groovy (groovy)
Now we are are en route to learn how to create tabs with ViewPager2.
SETTING UP THE ADAPTER FOR ViewPager2
Now here lies the groundbreaking change in the new library. Before we used to use the FragmentStatePagerAdapter
or something similar for ViewPager
.
But for ViewPager2
we will be using FragmentStateAdapter
which itself is a child of RecyclerView.Adapter
.
Look at the code below first
class Vp2Adapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
override fun getItemCount(): Int {
return 5
}
override fun createFragment(position: Int): Fragment {
return SimpleItemFragment.newInstance()
}
}
Code language: Kotlin (kotlin)
We will creating a new instance of the fragment for each tabs on createFragment()
here modify it as you like.
And, we must return the total number of tabs in getItemCount()
.
Also Read: Async Task in Android is Deprecated: There are Better Ways
TECHENUM
COMBINING EVERYTHING
First, we have to map the views to our fragment Vp2Fragment
. After that, we have to instantiate the adapter. And then we have to link the Vp2Adapter
with TabLayout
.
Let use look at the adapter setup part before we see our final code.
TabLayoutMediator( mTabLayout, mViewPager )
{ tab, position ->
// let us just name it Tab 1 to 5 ; modify it as your need
tab.text = "Tab #${position + 1}"
}.attach()
Code language: Kotlin (kotlin)
The TabLayoutMediator takes in three parameters TabLayout
, ViewPager2
and the Behaviour
. The code outside object in braces is the final parameter. It’s just cleaner way of passing things around.
Let us look at our full code:
class Vp2Fragment : Fragment() {
companion object {
fun newInstance() = Vp2Fragment()
}
private lateinit var mViewPager: ViewPager2
private lateinit var mTabLayout: TabLayout
private lateinit var mAdapter: Vp2Adapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.vp2_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mAdapter = Vp2Adapter(this)
mTabLayout = view.findViewById(R.id.tab_layout)
mViewPager = view.findViewById(R.id.view_pager)
mViewPager.adapter = mAdapter
TabLayoutMediator(
mTabLayout,
mViewPager
) { tab, position ->
tab.text = "Tab #${position + 1}"
}.attach()
}
}
Code language: Kotlin (kotlin)
Now all we have to do in our MainActivity
is add the fragment:
class MainActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager.beginTransaction()
.replace(R.id.container, Vp2Fragment.newInstance())
.commit()
}
}
Code language: Kotlin (kotlin)
In the code above the R.id.container
is the name of the container where the fragment will be put. And it is located in activity_main.xml
That’s it folks we have successfully learn to create tabs with ViewPager2
. Feel free to comment if I have missed anything.
For reference you can check out Android Documentation.