Android的FragmentStatePagerAdapter,如何标记一个片段之后找到它到它、片段、标记、Android

2023-09-03 23:21:41 作者:今夜无风无月

在使用 FragmentStatePageAdapter 我得到的片段是这样的:

When using the FragmentStatePageAdapter I get the fragments like this:

    @Override
    public Fragment getItem(int position) {
        return new SuperCoolFragment();
    }

不过,后来在我的code我需要找到这个片段设置属性。在应用程序的其他一些地方,我用我的片段基本上标记他们,找他们使用 findFragmentByTag(TAG)但现在我不知道该怎么做。

However, later on my code I need to find this fragment to set a property. In some other parts of the app where I use fragments I basically tag them and look for them using findFragmentByTag(TAG) but with now I don't know how to do it.

我如何能找到使用片段 FragmentStatePageAdapter

How do can I find the fragments using the FragmentStatePageAdapter?

推荐答案

最好的选择是这里的第二个解决方案: http://tamsler.blogspot.nl/2011/11/android-viewpager-and-fragments-part-ii.html

Best option is the second solution here: http://tamsler.blogspot.nl/2011/11/android-viewpager-and-fragments-part-ii.html

在短期:您跟踪所有的活动片段页面。在这种情况下,跟踪片段页面中FragmentStatePagerAdapter,用于由ViewPager的..

In short: you keep track of all the "active" fragment pages. In this case, you keep track of the fragment pages in the FragmentStatePagerAdapter, which is used by the ViewPager..

public Fragment getItem(int index) {
    Fragment myFragment = MyFragment.newInstance();
    mPageReferenceMap.put(index, myFragment);
    return myFragment;
}

要避免保持一个参考,以不活跃的片段页,我们需要实现FragmentStatePagerAdapter的destroyItem(...)方法:

To avoid keeping a reference to "inactive" fragment pages, we need to implement the FragmentStatePagerAdapter's destroyItem(...) method:

public void destroyItem(View container, int position, Object object) {
    super.destroyItem(container, position, object);
    mPageReferenceMap.remove(position);
}

...当你需要访问当前可见的页面,你再拨打:

... and when you need to access the currently visible page, you then call:

int index = mViewPager.getCurrentItem();
MyAdapter adapter = ((MyAdapter)mViewPager.getAdapter());
MyFragment fragment = adapter.getFragment(index);

...其中MyAdapter的getFragment(int)方法是这样的:

... where the MyAdapter's getFragment(int) method looks like this:

public MyFragment getFragment(int key) {
    return mPageReferenceMap.get(key);
}

---编辑:

---

另外补充这在您的适配器,一个方向变化后:

Also add this in your adapter, for after an orientation change:

/**
 * After an orientation change, the fragments are saved in the adapter, and
 * I don't want to double save them: I will retrieve them and put them in my
 * list again here.
 */
@Override
public Object instantiateItem(ViewGroup container, int position) {
    MyFragment fragment = (MyFragment) super.instantiateItem(container,
            position);
    mPageReferenceMap.put(position, fragment);
    return fragment;
}