当我迁移到ViewPager2时,遇到了类似的问题。
在我的情况下,我决定使用parentFragment属性(我认为你也可以让它适用于活动),并希望ViewPager2只保留当前片段处于恢复状态。(即最后一次被恢复的页片段是当前页。)
因此,在包含ViewPager2视图的主片段(HostFragment)中,我创建了以下属性:
private var _currentPage: WeakReference<MyPageFragment>? = null
val currentPage
get() = _currentPage?.get()
fun setCurrentPage(page: MyPageFragment) {
_currentPage = WeakReference(page)
}
我决定使用 WeakReference,这样我就不会泄漏不活动的Fragment实例。
我在 ViewPager2 中显示的每个Fragment都继承自通用超类 MyPageFragment。该类负责在 onResume 中向宿主Fragment注册其实例:
override fun onResume() {
super.onResume()
(parentFragment as HostFragment).setCurrentPage(this)
}
我还使用这个类来定义分页片段的通用接口:
abstract fun someOperation1()
abstract fun someOperation2()
然后我可以这样从HostFragment中调用它们:
currentPage?.someOperation1()
我不是说这是一个好的解决方案,但我认为它比之前我们必须使用的ViewPager适配器中的instantiateItem方法更加优雅。
fragmentManager.findFragmentById(getItemId(index).toInt())from within theFragmentStateAdapterseems to work but only after the fragment has been added. From the docs this may not work though if the fragments are moved.Default implementation works for collections that don't add, move, remove items- Markymark