0

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?

emen
  • 6,050
  • 11
  • 57
  • 94

1 Answers1

1

Notifying PagerAdapter is not gonna work for this .. You can do this in several way .

  1. Set new Adapter to ViewPager2 .

  2. 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 ..

  3. 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 .

ADM
  • 20,406
  • 11
  • 52
  • 83
  • Thanks for your input. For number 3, where do I put the receiver observable? Is it in the Adapter or the individual tabbed fragments? – emen Aug 26 '22 at 06:57
  • In `ProductFragment` Do not put anything in adapter .. keep it clean .. – ADM Aug 26 '22 at 07:09
  • I see, okay. But, how do I know to which `ProductFragment` it has to update? Since I'm using a ViewPager which has multiple fragments inside it. – emen Aug 26 '22 at 10:36