Migration from ViewPager to ViewPager2
Capabilities:
- Support Verticle Scroll
- Page Change Callback [onPageScrolled(), onPageSelected(), onPageScrollStateChanged()]
- Support Right-to-left tabs order
- Combined with the DiffUtil and other features backed by the recycler view (animations etc)
Changes Required for migration ViewPager -> ViewPager2
- Adapter parant class
from: class MyAdapter : PagerAdapter()
to: class MyAdapter : RecyclerView.Adapter<>()
// If using ViewPager with fragments
from: class MyFragmentAdapter( fm: FragmentManager ) : FragentStatePagerAdapter(fm, ...)
to: class MyFragmentAdapter( fa: FragmentActivity // or f: Fragment // or fm: FragmentManager, l: Lifecycle ) : FragentStateAdapter(fa, ...)
2. To get the count
from: override fun getCount(): Int {...}
to: override fun getItemCount(): Int {...}
3. To get Item
from: override fun getItem(postion: Int): Framgent {...}
to: override fun createFragment(postion: Int): Fragment {...}
To use tab layout with ViewPager2
- Tablayout decoupled from ViewPager2 and available in Material Components. So it is required to implement Material Desing library
- Changes required in the fragment
from: tabLayout.setupWithViewPager(viewPager);
to: TabLayouMediator (tablayout, viewpager){tab, postion -> // here we can modify the tabs tabs.text = "Item ${(position + 1)}" }.attach()