I have a FragmentStateAdapter as the adapter of a ViewPager2.
class DefaultFragmentStateAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
var items = listOf<Fragment>()
set(value) {
field = value
notifyDateSetChanged()
}
override fun getItemCount(): Int = items.size
override fun createFragment(position: Int): Fragment = items[position]
}
The adapters item can change depending on the date a user has selected, so it needs to be dynamical.
What happens is that after I call adapter.items = {new_fragments}
current fragment is not reloaded, only after I go to one of the last pages in the ViewPager and return to the first page can I see the updated fragment.
The current fragment does not update when notifyDataSetChanged
is called.
How can I manage to update current displayed fragment?
Just refresh your HomeFragment or ProfileFragment by overriding onResume method. In onResume Method you can refresh your ListFragment or Fragment easily.
As we already know that ViewPager2 is built on RecyclerView that's why it's easy to update only one item by calling the method notifyItemChanged(index). If we want to update all items then we can also do this by simply calling the notifyDatasetChanged() method. That's it for now.
The ViewPager and pager adapter just deal with data in memory. So when data in memory is updated, we just need to call the adapter's notifyDataSetChanged() . Since the fragment is already created, the adapter's onItemPosition() will be called before notifyDataSetChanged() returns.
FragmentStateAdapter instead. Implementation of PagerAdapter that uses a Fragment to manage each page. This class also handles saving and restoring of fragment's state. This version of the pager is more useful when there are a large number of pages, working more like a list view.
I had to override the following two methods...
override fun getItemId(position: Int): Long {
return items[position].id
}
override fun containsItem(itemId: Long): Boolean = items.any { it.id == itemId }
... to make it work!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With