当子元素被修改时, ViewPager2会转到第一页



我有一个ViewPager2与FragmentStateAdapter和未知数量的页面;每个Fragment子段内部都有一个recyclerView,所有Fragment子段之间都有一个共享的viewmodel。

我监听共享视图模型的livedata(因为所有片段都在监听相同的livedata);当livedata被触发时,我更新每个片段中的recyclerView。

然而,当recyclerview更新发生时,ViewPager会自动转到第一页,完全破坏了用户体验。

当数据被修改时,是否有办法不回到第一页?

#更新02/03/2021

我的FragmentStateAdapter子类:

class IngredientsViewPagerAdapter(fragment: Fragment, private val ingredientType: Int) :
FragmentStateAdapter(fragment) {
private var numberOfPages : Int = 0
fun setNumberOfPages(numberOfPages : Int){
if (this.numberOfPages != numberOfPages) {
this.numberOfPages = numberOfPages
notifyDataSetChanged()
}
}

override fun getItemCount(): Int {
return numberOfPages
}
override fun createFragment(position: Int): Fragment {
return CustomDrinkIngredientsPagerFragment.newInstance(position, ingredientType)
}}

使用的片段:

class CustomDrinkIngredientsPagerFragment : Fragment(R.layout.view_pager_standard_drinks),
IngredientsListAdapter.IngredientListAdapterInterface{
private val customDrinkViewModel : CustomDrinkViewModel by activityViewModels()
private lateinit var rvIngredients : RecyclerView
private val ingredientListAdapter = IngredientsListAdapter(emptyList(), this@CustomDrinkIngredientsPagerFragment)
private val position by lazy {
requireArguments().getInt("position")
}
private val ingredientType by lazy {
requireArguments().getInt("ingredientType")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
rvIngredients = view.findViewById(R.id.list_recycler_view)
rvIngredients.apply {
layoutManager =
GridLayoutManager(requireContext(), 4, GridLayoutManager.VERTICAL, false)
adapter = ingredientListAdapter
}
customDrinkViewModel.ingredients.observe(viewLifecycleOwner) {
ingredientListAdapter.submitList(it[ingredientType]!![position])
Log.d("ROB", "Observed ingredients iType:${ingredientType} position:${position}")
}
}
override fun onIngredientSelected(ingredient: Ingredient) {
customDrinkViewModel.addIngredient(ingredient)
}
companion object {
@JvmStatic
fun newInstance( position : Int, ingredientType : Int): CustomDrinkIngredientsPagerFragment{
val args = Bundle()
args.putInt("position", position)
args.putInt("ingredientType", ingredientType)
val fragment = CustomDrinkIngredientsPagerFragment()
fragment.arguments = args
return fragment
}
}}

我发现了问题:它是父ViewPager(上面的ViewPager)。我认为问题是第二个ViewPager,而不是它的父。

实际结构为:: viewpage→

修改第二个ViewPager子节点,通知第一个ViewPager子节点被修改,notifyDatasetChanged被自动触发(跳转到第0页)

相关内容

  • 没有找到相关文章

最新更新