To load single Fragment at a time you have to use ViewPager2
. Because FragmentStatePagerAdapter
is deprecated after API level 27.
Use Below steps to implement viewPager
with TabLayout
to load single fragment at time.
Step1: add tablayout nad viewpage in your xml file where you want to display multiple tab.
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="@dimen/dp_40"
android:id="@+id/tab_layout"/>
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:saveEnabled="false"
android:layout_height="match_parent"
android:id="@+id/viewpager" />
Step2: Then Create Adapter Class for your viewPager to manage your multiple Fragments.
class MyFragmentsAdapter(fm: FragmentManager,
private val totalTabs: Int,
lifecycle: Lifecycle) :
FragmentStateAdapter(fm, lifecycle) {
override fun getItemCount(): Int = totalTabs
override fun createFragment(position: Int): Fragment {
when (position) {
0 -> {
return NotificationsFragment()
}
1 -> {
return MessagesFragment()
}
2 -> {
return CalendarFragment()
}
else -> return NotificationsFragment()
}
}
}
Step3: Now attached this adapter class with your viewPager Object.
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.notification)))
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.messages)))
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.calendar)))
val adapter = NotificationTabsAdapter(
requireContext(),
childFragmentManager, tabLayout.tabCount,
lifecycle
)
viewPager.adapter = adapter
Step4: Now create ViewPager2.OnPageChangeCallback
method to manage tablayout status on ViewPager state change. Also register this method for viewpager using registerOnPageChangeCallback
val myPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
tabLayout.getTabAt(position)?.select()
}
}
viewPager.registerOnPageChangeCallback(myPageChangeCallback)
Step5: Now Register tablyout to change viewpager on tabItem click.
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
viewPager.currentItem = tab.position
}
override fun onTabUnselected(tab: TabLayout.Tab) {
}
override fun onTabReselected(tab: TabLayout.Tab) {
}
})