Home > Mobile >  How to replace fragment in ViewPager2
How to replace fragment in ViewPager2

Time:09-17

I have migrated ViewPager to ViewPager2 and adapter FragmentPageAdapter to FragmentStateAdaper. In FragmentPageAdapter there is a method called getItemPostion(Object obj) by using this method I can able to replace fragments. In FragmentStateAdaper class that method is not there how to replace fragments in viewpager2 with FragmentStateAdaper.

CodePudding user response:

You have to override createFragment(position: Int) method in FragmentStateAdapter which returns Fragment for respective positions.

createFragment can be override like this

override fun createFragment(position: Int): Fragment {
      return when (position) {
            0 -> FragmentOne()
            1 -> FragmentTwo()
            else -> FragmentOne()
        }
}

Apart from this, you also have to override getItemCount() in FragmentStateAdapter, where you have to return total number of fragments.

CodePudding user response:

in your activity set viewpager

private fun setTabs() {
        listFragmentTitles = arrayListOf("Fragment1","Fragment2","Fragment3")
        viewPagerFragmentAdapter = 
        ViewPagerFragmentAdapter(this,listFragmentTitles)
        binding.viewPager.adapter = viewPagerFragmentAdapter
        TabLayoutMediator(
            binding.tabLayout, binding.viewPager
        ) { tab: TabLayout.Tab, position: Int ->
            tab.text = listFragmentTitles[position]
        }.attach()
    }

view pager adapter

internal class ViewPagerFragmentAdapter(
    fragmentActivity: FragmentActivity,
    listFragmentTitles: ArrayList<String>
) :
    FragmentStateAdapter(fragmentActivity) {

    val titlesList = listFragmentTitles

    override fun createFragment(position: Int): Fragment {
        when (position) {
            0 -> return Fragment1()
            1 -> return Fragment2()
            2 -> return Fragment3()
        }
        return Fragment1()
    }

    override fun getItemCount(): Int {
        return titlesList.size
    }
}
  • Related