[英]Update whole ViewPager2 fragment contents
I have a ViewPager2 with TabLayout in a host fragment.我在主机片段中有一个带有 TabLayout 的 ViewPager2。
This ViewPager2 is also hosting several other fragments which contains a RecyclerView (A list).这个 ViewPager2 还托管了其他几个包含 RecyclerView(A 列表)的片段。
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.我的目标是我想更新 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.遍历单个 RecyclerView 适配器来更新它对我来说有点困难,所以我决定改为刷新顶级 ViewPager2 片段。
Unfortunately, after I send back the new data in the ViewPager2 adapter and calling notifyDataSetChanged()
, it's not working.不幸的是,在我在 ViewPager2 适配器中发回新数据并调用notifyDataSetChanged()
后,它不起作用。
My FragmentStateAdapter
look like this:我的FragmentStateAdapter
看起来像这样:
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:从 Host Fragment,ViewPager2 适配器设置如下:
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?如何刷新 ViewPager2 片段,以便用新数据刷新整个 RecyclerView?
Notifying PagerAdapter
is not gonna work for this.. You can do this in several way.通知PagerAdapter
对此不起作用。您可以通过多种方式执行此操作。
Set new Adapter to ViewPager2
.将新适配器设置为ViewPager2
。
You can get have a WeakReference
Fragment list inside your ProductAdapter
.您可以在ProductAdapter
中有一个WeakReference
Fragment 列表。 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 ie Your HostFragment
.与 Owner 共享ViewModel
是其中包含ViewPager2
的片段,即 Your HostFragment
。 This way you can listen for the changes in the products
list with an Observable like LiveData
and take action on it.通过这种方式,您可以使用LiveData
之类的 Observable 来监听products
列表中的变化并对其采取行动。 IMO this one is better way to do this. IMO 这是更好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.