如何获得使用FragmentPagerAdapter时,现有的片段
我有问题,让我的片段通过活动互相通信
,它是使用 FragmentPagerAdapter
,作为实现标签的管理和连接的 ViewPager
关联 TabHost
所有细节一个辅助类。因为它是由Android的示例项目提供我已实施 FragmentPagerAdapter
一样一样的 Support4Demos 的。
I have problem making my fragments communicating with each other through the Activity
, which is using the FragmentPagerAdapter
, as a helper class that implements the management of tabs and all details of connecting a ViewPager
with associated TabHost
. I have implemented FragmentPagerAdapter
just as same as it is provided by the Android sample project Support4Demos.
主要的问题是我怎么能获得 FragmentManager
特定片段时,我没有既没有标识或标签? FragmentPagerAdapter
是创建片段和自动生成的编号和标签。
The main question is how can I get particular fragment from FragmentManager
when I don't have neither Id or Tag? FragmentPagerAdapter
is creating the fragments and auto generating the Id and Tags.
我发现我的问题,根据下面的帖子回答:reusing在fragmentpageradapter 片段
I have found answer on my question based on following post: reusing fragments in a fragmentpageradapter
几件事情我已经学会了:
-
的getItem(INT位置)
在了这个方法实际执行FragmentPagerAdapter
是相当具误导性的名字。它创造了新的片段,不返回现有的。在这样的意义,该方法应该改名为类似于createItem中(INT位置)
在Android SDK。因此,这种方法并不能帮助我们获得片段。 - 在基于解释在后support FragmentPagerAdapterholds参考旧片段你应该把创建片段到
FragmentPagerAdapter
并在这样意味着你有没有可参考的碎片或他们的标签。如果你有片段的标签,虽然,你可以轻松地检索调用引用它从FragmentManager
findFragmentByTag()
。我们需要一种方法来找出一个片段,在给定的页面位置的标记。
-
getItem(int position)
in theFragmentPagerAdapter
is rather misleading name of what this method actually does. It creates new fragments, not returning existing ones. In so meaning, the method should be renamed to something likecreateItem(int position)
in the Android SDK. So this method does not help us getting fragments. - Based on explanation in the post support FragmentPagerAdapterholds reference to old fragments you should leave the creation of the fragments to the
FragmentPagerAdapter
and in so meaning you have no reference to the Fragments or their tags. If you have fragment tag though, you can easily retrieve reference to it from theFragmentManager
by callingfindFragmentByTag()
. We need a way to find out tag of a fragment at given page position.
解决方案
添加下面的辅助方法,在你的类来检索片段标记,并将其发送到 findFragmentByTag()
方法。
Add following helper method in your class to retrieve fragment tag and send it to the findFragmentByTag()
method.
private String getFragmentTag(int viewPagerId, int fragmentPosition)
{
return "android:switcher:" + viewPagerId + ":" + fragmentPosition;
}
请注意!这是 FragmentPagerAdapter
利用创造新的片段时相同的方法。看到这个链接http://$c$c.google.com/p/openintents/source/browse/trunk/compatibility/AndroidSupportV2/src/android/support/v2/app/FragmentPagerAdapter.java#104
NOTE! This is identical method that FragmentPagerAdapter
use when creating new fragments. See this link http://code.google.com/p/openintents/source/browse/trunk/compatibility/AndroidSupportV2/src/android/support/v2/app/FragmentPagerAdapter.java#104