使用ViewPager2获取当前片段 [英] Get current fragment with ViewPager2

查看:1954
本文介绍了使用ViewPager2获取当前片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的ViewPager迁移到ViewPager2,因为后者应该可以解决前者的所有问题.不幸的是,当将它与FragmentStateAdapter一起使用时,我找不到任何方法来获取当前显示的片段.

I'm migrating my ViewPager to ViewPager2 since the latter is supposed to solve all the problems of the former. Unfortunately, when using it with a FragmentStateAdapter, I don't find any way to get the currently displayed fragment.

viewPager.getCurrentItem()给出当前显示的索引,而adapter.getItem(index)通常为当前索引创建一个新的Fragment.除非在getItem()中保留对所有已创建片段的引用,否则我不知道如何访问当前显示的片段.

viewPager.getCurrentItem() gives the current displayed index and adapter.getItem(index) generally creates a new Fragment for the current index. Unless keeping a reference to all created fragments in getItem(), I have no idea how to access the currently displayed fragment.

使用旧的ViewPager,一种解决方案是调用adapter.instantiateItem(index),它将以所需的索引返回该片段.

With the old ViewPager, one solution was to call adapter.instantiateItem(index) which would return the fragment at the desired index.

我是否缺少ViewPager2的东西?

推荐答案

迁移到ViewPager2时,我遇到了类似的问题.

I had similar problem when migrating to ViewPager2.

在我的情况下,我决定使用parentFragment属性(我认为您也可以将其用于活动),并希望ViewPager2仅保留当前片段. (即最后恢复的页面片段是当前片段.)

In my case I decided to use parentFragment property (I think you can make it also work for activity) and hope, that ViewPager2 will keep only the current fragment resumed. (i.e. page fragment that was resumed last is the current one.)

因此,在包含ViewPager2视图的主片段(HostFragment)中,我创建了以下属性:

So in my main fragment (HostFragment) that contains ViewPager2 view I created following property:

private var _currentPage: WeakReference<MyPageFragment>? = null
val currentPage
    get() = _currentPage?.get()

fun setCurrentPage(page: MyPageFragment) {
    _currentPage = WeakReference(page)
}

我决定使用WeakReference,所以我不会泄漏不活动的Fragment实例

I decided to use WeakReference, so I don't leak inactive Fragment instances

我在ViewPager2中显示的每个片段都继承自普通的超类MyPageFragment.此类负责向onResume中的主机片段注册其实例:

And each of my fragments that I display inside ViewPager2 inherits from common super class MyPageFragment. This class is responsible for registering its instance with host fragment in onResume:

override fun onResume() {
    super.onResume()
    (parentFragment as HostFragment).setCurrentPage(this)
}

我还使用此类定义了分页片段的通用接口:

I also used this class to define common interface of paged fragments:

abstract fun someOperation1()

abstract fun someOperation2()

然后我可以像这样从HostFragment调用它们:

And then I can call them from the HostFragment like this:

currentPage?.someOperation1()

我并不是说这是一个不错的解决方案,但我认为它比以前依赖于ViewPager's适配器内部和我们以前使用过的instantiateItem方法更为优雅.

I'm not saying it's a nice solution, but I think it's more elegant than relying on internals of ViewPager's adapter with instantiateItem method that we had to use before.

这篇关于使用ViewPager2获取当前片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆