How to get the current fragment displayed in a specific tab of a viewpager?(如何让当前片段显示在 viewpager 的特定选项卡中?)
问题描述
我想在 tab b_1
中获取 backstack 中的最后一个片段,或者当前显示的片段对我来说是一样的.如下图所示,我有一个 ViewPager,还有一个内部 tab b
.因此显示了四个当前片段.
I want to get the last fragment in the backstack, or the current displayed it's the same for me, in the tab b_1
. As you can see in the following image, I have a ViewPager, and another one inner tab b
. Thus there are four current fragments displayed.
问题:如何获取Fragment 2
实例?
我见过另一种解决方案,但没有一个适用于这种情况.
I have seen another solutions, but none works for this scenario.
注解:要返回的片段不必托管在 ViewPager 中.我可以在一个选项卡中再打开两个片段.
Annotation: The fragment to return is not necessary the hosted in the ViewPager. I can have opened two more fragments in a tab.
通过这种方法,我得到了所有当前可见的片段,但不是我想要的那个.
With this method I get all the current visible fragments, but not the one specific I want.
一些有趣的代码
activity_main.xml
activity_main.xml
MainActivity.java
MainActivity.java
fragment_host.xml
fragment_host.xml
HostFragment.java
HostFragment.java
fragment2_root.xml
fragment2_root.xml
RootFragment2.java
RootFragment2.java
推荐答案
首先在您的 ViewPagers
' 适配器中定义一个 SparseArray
,如下所示.在这个数组中,我们将保存片段的实例.
First define a SparseArray
in your ViewPagers
' adapters like below. In this array we'll hold the instance of fragments.
并覆盖适配器的 instantiateItem
方法.
And Override your Adapters' instantiateItem
method.
同时覆盖 ViewPagers
并定义一个新方法来获取您的 ViewPager
Fragments
实例.
And define a new method to get your ViewPager
Fragments
instance.
最后设置添加一个 PageChangeListener
到你的 ViewPagers
:
And finally set add a PageChangeListener
to your ViewPagers
:
我希望这会对你有所帮助.祝你好运.
I hope this'll help you. Good luck.
对不起,我无法准确理解您打算做什么,但如果您需要保留子片段 (b_1, b_2) 实例,您可以为您的活动定义一个方法,例如
I'm sorry i cannot understand exactly what you're planning to do but if you need to keep sub fragment (b_1, b_2) instance you can define a method to your activity such as
在您的子视图寻呼机的适配器中,您可以像下面这样调用此方法:
and in your sub view pager's adapter you can call this method like below:
通过这种方式,您可以保留一个实例和您的顶部片段.
With this way you can keep one instance and your top fragment.
这篇关于如何让当前片段显示在 viewpager 的特定选项卡中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!