I have a ViewPager2 using FragmentStateAdapter and some inner RecyclerView inside the ViewPager2.
I need to update the data in the individual row of the RV. However, whenever I update the adapter, the list scrolls to top automatically which I want to prevent.
The data I'm passing to the FragmentStateAdapter looks like this:
[
ProductWithCategory
categoryName = String
products = [
Product(id, name, code, isSelected),
Product(id, name, code, isSelected),
Product(id, name, code, isSelected),
Product(id, name, code, isSelected)
],
ProductWithCategory
categoryName = String
products = [
Product(id, name, code, isSelected),
Product(id, name, code, isSelected),
Product(id, name, code, isSelected),
Product(id, name, code, isSelected)
],
.
.
.
]
Note that I'm particularly want to update the isSelected field. categoryName is used as TabLayout title.
My current solution is to reset the whole adapter to update the whole fragments inside the ViewPager2, hence the scroll to top issue occurs.
I know it should have been done by notifyDatasetChanged() inside the RecyclerView adapter, but I don't know how to pass the updated data to the adapter with the model I have above.
private fun setupTabLayout(productWithCategory: List<ProductWithCategory>) {
tabMenuBinding.apply {
val adapter = ProductTypeAdapter(
fragment = this,
productWithCategory = productWithCategory
)
viewPager.adapter = adapter
val tabMediator = TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = productWithCategory[position].categoryName
}
tabMediator.attach()
}
}
My FragmentStateAdapter look like this:
class ProductAdapter(
fragment: Fragment,
private val products: List<ProductWithCategory>
) : FragmentStateAdapter(fragment) {
override fun getItemCount() = products.size
override fun createFragment(position: Int): Fragment {
return ProductsFragment(products[position].products)
}
}
In the RecyclerView adapter looks like this:
class ProductsFragment(
private val products: List<Products>
) : BaseFragment() {
override fun getLayoutRes(): Int = R.layout.fragment_list_item
override fun setupView(view: View) {
val adapter = ListItemAdapter(products)
binding.rvList.adapter = adapter
}
}
How can I update the data of the inner RecyclerView to prevent auto-scroll to top when adapter is reset?