I am using a ViewPager2 together with an adapter that minimally extends FragmentStateAdapter, as follows:
class MyAdapter(fragment: Fragment): FragmentStateAdapter(fragment) {
override fun createFragment(position: Int): Fragment {
return MyFragment.newInstance(position)
}
override fun getItemCount(): Int {
return 5
}
}
Unfortunately, calling notifyDataSetChanged() on the adapter has no effect at all. (Calling notifyItemChanged(position) works fine.)
How can I solve this?
I've created a bug report for this here in IssueTracker. For me, though, even the
notifyItemChanged(position:)andnotifyItemRangeChanged(positionStart:itemCount:)methods behave incorrectly.The bug is due to the default implementation of the
FragmentStateAdapter.getItemId(position:)method which simply returns thepositionpassed into it. TheitemIdfor eachpositionwill therefore be the same before and after aFragmentStateAdapter.notifyDataSetChanged()call and therefore none of theFragments will ever be recreated.One possible workaround is to assign each page a unique id within your
FragmentStateAdapterimplementation and to assign a new id to each page whenever thenotifyDataSetChanged()method is called. See theinitblock in theViewPagerAdapterclass below which facilitates this workaround: AnAdapterDataObserverobject is registered in thisinitblock such that it receives a callback whenevernotifyDataSetChanged()is called.