【问题标题】:Determining when fragment no longer visible in ViewPager2确定片段何时在 ViewPager2 中不再可见
【发布时间】:2020-06-22 03:56:35
【问题描述】:

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

使用ViewPager,我可以覆盖ListFragmentFragmentPagerAdapter 中的setPrimaryItem,以了解何时一页替换另一页。至关重要的是,此函数将实际可见的子片段作为参数,我可以将其存储在适配器中,然后在它被另一个片段替换时用于取消批量编辑。

我如何对ViewPager2 做同样的事情,即知道片段何时不再可见?我尝试过覆盖Fragment.onPause,但这不是我想要的——只要手机屏幕关闭或方向改变,它就会被调用,我不想在这些情况下取消批量编辑。我也有一个通过ViewPager2.registerOnPageChangeCallback 注册的回调,但这只会给我新片段的索引,而不是片段本身或旧片段的任何信息。

【问题讨论】:

    标签: android android-fragments android-viewpager2


    【解决方案1】:

    我认为最好的解决方案是注册FragmentTransactionCallback。缺点 - 仅在 ViewPager2 库的 the latest 1.1.0 alpha release 中添加。

    该类 (FragmentTransactionCallback::onFragmentMaxLifecyclePreUpdated) 上有一个方法,每当 ViewPager2 更改 a Fragment's maximum Lifecycle state 时都会调用该方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-23
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多