我有viewPager2和FragmentStateAdapter,还有Fragement1、2,3 4,我在fragment2,想去掉fragment3,在fragment2之后显示fragment4。问题是它总是显示片段3(数据),调试显示片段3已被删除,但显示的页面仍然有片段3内容。
适配器:
class TipsAdapter(
private val items: MutableList<TripPage>,
context: FragmentActivity
) : FragmentStateAdapter(context) {
private val fragmentFactory = context.supportFragmentManager.fragmentFactory
private val classLoader = context.classLoader
override fun getItemCount(): Int = items.size
override fun createFragment(position: Int): Fragment {
val pageInfo = items[position]
val fragment = fragmentFactory.instantiate(classLoader, pageInfo.fragmentClass.name)
fragment.arguments = Bundle().also { it.putParcelable(PAGE_INFO, pageInfo) }
return fragment
}
fun getFragmentName(position: Int) = items[position].fragmentClass.simpleName
fun removeFragment(position: Int) {
items.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, items.size)
notifyDataSetChanged()
}
}
删除片段代码:
if ((view_pager.adapter as TipsAdapter).getFragmentName(index + 1).equals(
TripPreFragment::class.simpleName) &&
viewModel.shouldRemoveBulkApply()) {
(view_pager.adapter as TipsAdapter).removeFragment(index + 1)
view_pager.setCurrentItem(index + 1, true)
} else {
view_pager.setCurrentItem(index + 1, true)
}