Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FragmentStateAdapter not recreating currentFragment after notifyDataSetChanged

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?

like image 509
Manuel Munoz Avatar asked Mar 31 '20 20:03

Manuel Munoz


People also ask

How do I refresh FragmentStateAdapter?

Just refresh your HomeFragment or ProfileFragment by overriding onResume method. In onResume Method you can refresh your ListFragment or Fragment easily.

How do I refresh ViewPager2?

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.

How do I update my Android ViewPager adapter?

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.

What is FragmentStateAdapter?

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.


1 Answers

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!

like image 85
Manuel Munoz Avatar answered Oct 27 '22 21:10

Manuel Munoz