在fragmentpageradapter中重用片段

jwa*_*nga 70 android fragment android-compatibility android-fragments

我有一个浏览片段的viewpager.我的FragmentPagerAdapter子类在getItem方法中创建了一个看似浪费的新片段.是否有一个FragmentPagerAdapter相当于convertViewlistAdapter,使我重新使用已创建的片段?我的代码如下.

public class ProfilePagerAdapter extends FragmentPagerAdapter {

    ArrayList<Profile> mProfiles = new ArrayList<Profile>();

    public ProfilePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    /**
     * Adding a new profile object created a new page in the pager this adapter is set to.
     * @param profile
     */
    public void addProfile(Profile profile){
        mProfiles.add(profile);
    }

    @Override
    public int getCount() {
        return mProfiles.size();
    }

    @Override
    public Fragment getItem(int position) {
        return new ProfileFragment(mProfiles.get(position));
    }
}
Run Code Online (Sandbox Code Playgroud)

Geo*_*off 102

FragmentPagerAdapter已缓存Fragments为您服务.每个片段都分配了一个标签,然后FragmentPagerAdapter尝试调用findFragmentByTag.它只调用getItem如果从结果findFragmentByTagnull.所以你不应该自己缓存片段.

  • 是的,很明显这个方法是否被命名为'createItem' (17认同)
  • 蝙蝠我认为这不是解决方案.我有类似的问题.我在ViewPager中有10个屏幕,它们都包含只有不同参数的相同片段.我不需要10个实例.3是应该的.当用户向右滚动时,大多数左侧片段可以重复使用. (4认同)
  • @MattTaylor如果您使用的是ViewPager,可以使用setOffscreenPageLimit来保持相同的实例 (2认同)

pet*_*ejl 67

杰夫的帖子附录:

您可以参考您FragmentFragmentPagerAdapter使用情况findFragmentByTag().标记的名称以这种方式生成:

private static String makeFragmentName(int viewId, int index)
{
     return "android:switcher:" + viewId + ":" + index;
}
Run Code Online (Sandbox Code Playgroud)

其中viewId是ViewPager的id

请看这个链接:http://code.google.com/p/openintents/source/browse/trunk/compatibility/AndroidSupportV2/src/android/support/v2/app/FragmentPagerAdapter.java#104

  • 请注意像我这样的人:viewId是ViewPager的id (19认同)
  • 我的FragmentActivity中的一些工作代码:http://pastebin.com/XuGwNEG1 (3认同)

Ton*_*han 23

似乎很多人在查看这个问题时都在寻找一种方法来引用FragmentsFragmentPagerAdapter/ 创建的FragmentStatePagerAdapter.我想提供我的解决方案,而不依赖于内部创建tags的其他答案在这里使用.

作为奖励,这种方法也应该有效FragmentStatePagerAdapter.请参阅下面的注释以获取更多详


当前解决方案的问题:依赖内部代码

我在这个和类似问题上看到的很多解决方案都依赖于Fragment通过调用FragmentManager.findFragmentByTag()和模仿内部创建的标记"android:switcher:" + viewId + ":" + id来获取对现有的引用:.这样做的问题在于你依赖于内部源代码,我们都知道并不能保证它们永远保持不变.Google的Android工程师可以轻松决定更改tag会破坏您的代码的结构,从而无法找到对现有代码的引用Fragments.

替代解决方案,不依赖于内部 tag

这是一个简单的例子,说明如何获取对Fragments返回的引用FragmentPagerAdapter,而不依赖于内部tagsFragments.关键是instantiateItem()在那里覆盖和保存引用而不是getItem().

public class SomeActivity extends Activity {
    private FragmentA m1stFragment;
    private FragmentB m2ndFragment;

    // other code in your Activity...

    private class CustomPagerAdapter extends FragmentPagerAdapter {
        // other code in your custom FragmentPagerAdapter...

        public CustomPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // Do NOT try to save references to the Fragments in getItem(),
            // because getItem() is not always called. If the Fragment
            // was already created then it will be retrieved from the FragmentManger
            // and not here (i.e. getItem() won't be called again).
            switch (position) {
                case 0:
                    return new FragmentA();
                case 1:
                    return new FragmentB();
                default:
                    // This should never happen. Always account for each position above
                    return null;
            }
        }

        // Here we can finally safely save a reference to the created
        // Fragment, no matter where it came from (either getItem() or
        // FragmentManger). Simply save the returned Fragment from
        // super.instantiateItem() into an appropriate reference depending
        // on the ViewPager position.
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
            // save the appropriate reference depending on position
            switch (position) {
                case 0:
                    m1stFragment = (FragmentA) createdFragment;
                    break;
                case 1:
                    m2ndFragment = (FragmentB) createdFragment;
                    break;
            }
            return createdFragment;
        }
    }

    public void someMethod() {
        // do work on the referenced Fragments, but first check if they
        // even exist yet, otherwise you'll get an NPE.

        if (m1stFragment != null) {
            // m1stFragment.doWork();
        }

        if (m2ndFragment != null) {
            // m2ndFragment.doSomeWorkToo();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者如果您更喜欢使用tags而不是使用类成员变量/引用,Fragments您也可以tags通过FragmentPagerAdapter相同的方式获取该集:注意:这不适用于FragmentStatePagerAdapter因为它tags在创建时没有设置Fragments.

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
    // get the tags set by FragmentPagerAdapter
    switch (position) {
        case 0:
            String firstTag = createdFragment.getTag();
            break;
        case 1:
            String secondTag = createdFragment.getTag();
            break;
    }
    // ... save the tags somewhere so you can reference them later
    return createdFragment;
}
Run Code Online (Sandbox Code Playgroud)

请注意,此方法不依赖于模仿内部tag集合FragmentPagerAdapter,而是使用适当的API来检索它们.这种方式即使你tag未来版本的变化SupportLibrary仍然是安全的.


不要忘记,根据您的设计Activity,Fragments您正在尝试的工作可能存在,也可能不存在,因此您必须null在使用引用之前通过检查来解释这一点.

另外,如果您正在使用FragmentStatePagerAdapter,那么您不希望保留对您的硬引用,Fragments因为您可能有许多引用,并且硬引用会不必要地将它们保留在内存中.而是将Fragment引用保存在WeakReference变量而不是标准变量中.像这样:

WeakReference<Fragment> m1stFragment = new WeakReference<Fragment>(createdFragment);
// ...and access them like so
Fragment firstFragment = m1stFragment.get();
if (firstFragment != null) {
    // reference hasn't been cleared yet; do work...
}
Run Code Online (Sandbox Code Playgroud)

  • 这完全有效.非常感谢. (3认同)

Dan*_*eón 17

如果片段仍在内存中,您可以使用此功能找到它.

public Fragment findFragmentByPosition(int position) {
    FragmentPagerAdapter fragmentPagerAdapter = getFragmentPagerAdapter();
    return getSupportFragmentManager().findFragmentByTag(
            "android:switcher:" + getViewPager().getId() + ":"
                    + fragmentPagerAdapter.getItemId(position));
}
Run Code Online (Sandbox Code Playgroud)

v4支持api的示例代码.