ViewPager2中如何确定片段不再可见?

3

我想从ViewPager迁移到ViewPager2。 我现有的ViewPager包含支持通过ActionMode进行批量编辑的ListFragment。 当用户从一个页面滑动到另一个页面时,我需要取消当前的批量编辑操作,以避免在查看不同页面时显示来自另一页的上下文标题。

使用ViewPager,我可以在ListFragmentFragmentPagerAdapter中覆盖setPrimaryItem,以知道何时替换了一个页面。 关键是,该函数以一个实际变为可见的子片段作为参数,我可以将其存储在适配器中,并在其被另一个片段替换时稍后用于取消批量编辑。

如何在ViewPager2中执行相同的操作,即知道何时不再显示片段? 我尝试重写Fragment.onPause,但这并不是我想要的---它会在手机屏幕关闭或方向更改时调用,而我不想在这些情况下取消批量编辑。 我还通过ViewPager2.registerOnPageChangeCallback注册了回调,但这仅给我提供了新片段的索引,没有关于旧片段的信息,也没有提供片段本身。

1个回答

3
我认为最好的解决方法是注册一个 FragmentTransactionCallback。缺点是,这只在最新的 ViewPager2 库1.1.0 alpha 版本中添加了。
该类有一个方法 (FragmentTransactionCallback::onFragmentMaxLifecyclePreUpdated),每当 ViewPager2 更改 Fragment 的最大生命周期状态 时就会调用该方法。
val basicAdapter: FragmentStateAdapter = // ....

basicAdapter.registerFragmentTransactionCallback(object : FragmentTransactionCallback() {
    override fun onFragmentMaxLifecyclePreUpdated(fragment: Fragment, max: Lifecycle.State): OnPostEventListener {
        // Check whether a Fragment is going to move from 'resumed' to 'started'
        //
        // Note that this check won't catch some types of smooth scroll:
        // I'm not certain why, but I think it has to do with fragments
        // already being paused before the method is called.
        //
        if (max == Lifecycle.State.STARTED && fragment.isResumed) {
            // This fragment WAS the 'current item' but it's offscreen now.
            return OnPostEventListener { TODO("Cancel Bulk Editing") }
        }
        return super.onFragmentMaxLifecyclePreUpdated(fragment, max)
    }
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接