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

查看:78
本文介绍了使用 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 的某些内容?

Am I missing something with ViewPager2?

推荐答案

ViewPager2 中,FragmentManager 默认为片段分配了这样的标签:

In ViewPager2 the FragmentManager by default have assigned tags to fragments like this:

第一个位置的片段有一个标签 f0"

Fragment in 1st position has a tag of "f0"

第二个位置的片段有一个标签 f1"

Fragment in 2nd position has a tag of "f1"

第三个位置的片段有一个 "f2" 标签等等......所以你可以得到片段的标签,并通过连接f"与你的片段的位置.要获取当前片段,您可以从 viewPager2 位置获取当前位置并使您的标签像这样(对于 Kotlin):

Fragment in 3rd position has a tag of "f2" and so on... so you can get your fragment's tag and by concatenating the "f" with position of your fragment. To get the current Fragment you can get current position from the viewPager2 position and make your tag like this (For Kotlin):

val myFragment = supportFragmentManager.findFragmentByTag("f" + viewpager.currentItem)

对于某个位置的片段

val myFragment = supportFragmentManager.findFragmentByTag("f" + position)

如果您使用这种技术,您可以投射 Fragment 并始终检查它是否为空.

You can cast the Fragment and always check if it is not null if you are using this technique.

如果您在 Fragment 中托管 ViewPager2,请改用 childFragmentManager.

If you host your ViewPager2 in Fragment, use childFragmentManager instead.

记住

如果您在适配器中覆盖 getItemId(position: Int).那你的情况就不一样了.应该是:

If you have overriden the getItemId(position: Int) in your adapter. Then your case is different. It should be:

val myFragment = supportFragmentManager.findFragmentByTag("f" + your_id_at_that_position)

或者简单地说:

val myFragment = supportFragmentManager.findFragmentByTag("f" + adapter.getItemId(position))

如果您在 Fragment 中托管 ViewPager2,请使用 childFragmentManager 而不是 supportFragmentManager.

If you host your ViewPager2 in Fragment, use childFragmentManager instead of supportFragmentManager.

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

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