-1

I have a ViewPager that displays 10 fragments. However when I change the FragmentPagerAdapter and set it to the ViewPager only the not-currently-shown fragments are changed. I tried invalidating the ViewPager, calling notifyDataSetChanged() in the FragmentPagerAdapter and this SO answer and only changing the data instead of the adapter(and this answer is using a PagerAdapter instead of FragmentPagerAdapter but without success.

This is how I initialize the ViewPager

viewPager = rootView.findViewById(R.id.view_pager)
changeData()

and then later for changing I call this function

fun changeData(params: List<CustomObject> = ArrayList()){
    viewPager.adapter = CustomCPagerAdapter(fragmentManager!!, params)
}

and the CustomPagerAdapter

class CustomPagerAdapter(fm: FragmentManager,
                         private var customDataSet: List<CustomObject>) 
    : FragmentPagerAdapter(fm) {  

    override fun getItem(pos: Int): Fragment {
        return CustomFragment.newInstance(customDataSet[pos])
    }

    override fun getCount(): Int {
        return customDataSet.size
    }
}

Why is the ViewPager keeping the displayed fragments even though a new FragmentPagerAdapter is added to it? How do I change this?

Viktor Stojanov
  • 708
  • 6
  • 20

2 Answers2

0

Try this:-

fun changeData(params: List<CustomObject> = ArrayList()){
    viewPager.adapter = null 
    viewPager.adapter = CustomCPagerAdapter(fragmentManager!!, params)
}
Shubham Raitka
  • 1,034
  • 8
  • 15
0

The solution is to use FragmentStatePagerAdapter instead of FragmentPagerAdapter because it doesn't keep the fragments in memory. The later adapter has some sort of optimization and doesn't force refresh already displayed fragments even when a new instance of FragmentPagerAdapter is set to the ViewPager.

From the docs about FragmentStatePagerAdapter

This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.

Viktor Stojanov
  • 708
  • 6
  • 20