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 theposition
passed into it. TheitemId
for eachposition
will therefore be the same before and after aFragmentStateAdapter.notifyDataSetChanged()
call and therefore none of theFragment
s will ever be recreated.One possible workaround is to assign each page a unique id within your
FragmentStateAdapter
implementation and to assign a new id to each page whenever thenotifyDataSetChanged()
method is called. See theinit
block in theViewPagerAdapter
class below which facilitates this workaround: AnAdapterDataObserver
object is registered in thisinit
block such that it receives a callback whenevernotifyDataSetChanged()
is called.