ViewPager2无法动态添加删除片段 [英] ViewPager2 not able to dynamically add remove fragment
问题描述
在索引处删除/添加片段会导致Viewpager2中出现意外行为.对于ViewPager
,这是不可能的,但希望与Viewpager2
一起工作.这会导致重复的片段并且不同步TabLayout
.
这是一个演示项目,它再现了此问题.有一个切换按钮,可删除片段并将其重新连接到特定索引.在这种情况下,附加的片段应为绿色,但应为蓝色,并且以某种方式有2个蓝色片段.
Removing/Adding fragments at index results in unexpected behaviour in Viewpager2. This was not possible with ViewPager
but expected to work with Viewpager2
. It causes duplicate fragments and out of sync TabLayout
.
Here is a demo project which reproduces this issue. There is a toggle button which removes a fragment and reattaches it at a particular index. In this case attached fragment should be green but it's blue and there are 2 blue fragments somehow.
这是我的适配器的外观
class ViewPager2Adapter(activity: FragmentActivity) : FragmentStateAdapter(activity) {
val fragmentList: MutableList<FragmentName> = mutableListOf()
override fun getItemCount(): Int {
return fragmentList.size
}
override fun createFragment(position: Int): Fragment {
return when (fragmentList[position]) {
FragmentName.WHITE -> WhiteFragment()
FragmentName.RED -> RedFragment()
FragmentName.GREEN -> GreenFragment()
FragmentName.BLUE -> BlueFragment()
}
}
fun add(fragment: FragmentName) {
fragmentList.add(fragment)
notifyDataSetChanged()
}
fun add(index: Int, fragment: FragmentName) {
fragmentList.add(index, fragment)
notifyDataSetChanged()
}
fun remove(index: Int) {
fragmentList.removeAt(index)
notifyDataSetChanged()
}
fun remove(name: FragmentName) {
fragmentList.remove(name)
notifyDataSetChanged()
}
enum class FragmentName {
WHITE,
RED,
GREEN,
BLUE
}
}
我也已经向Google提交了 bug
I have filed a bug with google as well
推荐答案
如果在ViewPager2
override fun getItemId(position: Int): Long {
return fragmentList[position].ordinal.toLong()
}
override fun containsItem(itemId: Long): Boolean {
val fragment = FragmentName.values()[itemId.toInt()]
return fragmentList.contains(fragment)
}
将这两个添加到当前适配器中可以解决此问题
Adding these two in my current adapter fixes the problem
这篇关于ViewPager2无法动态添加删除片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!