使用FragmentStateAdapter移除viewPager2中的片段,但仍显示

时间:2019-09-14 20:11:44

标签: android android-viewpager fragmentstatepageradapter android-viewpager2

我有一个viewPager2和FragmentStateAdapter,并且有Fragement1、2、3、4,我在fragment2中,想要删除fragment3,并在fragment2之后显示fragment4。 问题是它总是向我显示fragment3(data),调试显示fragment3已被删除,但是显示的页面仍然具有fragment3内容。

适应者:

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)
        }

1 个答案:

答案 0 :(得分:1)

最后,它对我有用。当我们调用MessageBox时,android会调用  适配器中的方法notifyDataSetChanged(),以检查项目是否已更新。它返回源代码中的位置。这意味着在列表getItemId()中,如果删除0..i..n,它将变成i0...i...n-1不会更改,数据也不会自动更新。

i

您需要做的是重写此方法和 /** * Default implementation works for collections that don't add, move, remove items. * <p> * TODO(b/122670460): add lint rule * When overriding, also override {@link #containsItem(long)}. * <p> * If the item is not a part of the collection, return {@link RecyclerView#NO_ID}. * * @param position Adapter position * @return stable item id {@link RecyclerView.Adapter#hasStableIds()} */ @Override public long getItemId(int position) { return position; }

对于我来说,我使用每个片段的哈希码:

containsItem(long)

}