Reputation: 6318
I have a ViewPager2 with TabLayout in a host fragment.
This ViewPager2 is also hosting several other fragments which contains a RecyclerView (A list).
Host_Fragment
-> ViewPager2 (FragmentStateAdapter)
-> Fragment1
- RV + Adapter
-> Fragment2
- RV + Adapter
-> Fragment3
- RV + Adapter
My goal is I want to update the data in the list in RecyclerView. It's kinda hard for me to traverse back to the individual RecyclerView adapter to update it, so I decided to refresh the top level ViewPager2 fragments instead.
Unfortunately, after I send back the new data in the ViewPager2 adapter and calling notifyDataSetChanged()
, it's not working.
My FragmentStateAdapter
look like this:
class ProductAdapter(
fragment: Fragment,
private val products: List<Data>
) : FragmentStateAdapter(fragment) {
private var mutableList = products.toMutableList()
override fun getItemCount() = products.size
override fun createFragment(position: Int): Fragment {
return ProductsFragment(mutableList[position].products)
}
// here i want to update the contents of this ViewPager2 with new set of data
fun updateItem(updatedData: List<Data>) {
mutableList.clear()
mutableList.addAll(updatedData)
notifyDataSetChanged()
}
}
And I want to supply the new set of data like this:
// do modification to listProducts
adapter.updateItem(listProducts)
From Host Fragment, ViewPager2 adapter is set up like this:
adapter = ProductAdapter(
fragment = this@HostFragment,
products = listProducts
)
viewPager.adapter = adapter
How do I refresh the ViewPager2 fragments, so that it refreshes the whole RecyclerView with new data?
Upvotes: 0
Views: 781
Reputation: 21043
Notifying PagerAdapter
is not gonna work for this .. You can do this in several way .
Set new Adapter to ViewPager2
.
You can get have a WeakReference
Fragment list inside your ProductAdapter
. this way you can access each fragment and call any method of these fragment to update the data . you can also get the fragment this way ..
Have a shared ViewModel
with Owner being the fragment which has the ViewPager2
in it i.e Your HostFragment
. This way you can listen for the changes in the products
list with an Observable like LiveData
and take action on it . IMO this one is better way to do this .
Upvotes: 1