在 fragmentpageradapter 中重用片段 [英] reusing fragments in a fragmentpageradapter

查看:32
本文介绍了在 fragmentpageradapter 中重用片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 viewpager 可以浏览片段.我的 FragmentPagerAdapter 子类在 getItem 方法中创建了一个看起来很浪费的新片段.是否有与 listAdapter 中的 convertView 等效的 FragmentPagerAdapter 使我能够重用已创建的片段?我的代码如下.

I have a viewpager that pages through fragments. My FragmentPagerAdapter subclass creates a new fragment in the getItem method which seems wasteful. Is there a FragmentPagerAdapter equivalent to the convertView in the listAdapter that will enable me to reuse fragments that have already been created? My code is below.

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));
    }
}

推荐答案

FragmentPagerAdapter 已经为你缓存了 Fragments.每个片段都分配了一个标签,然后 FragmentPagerAdapter 尝试调用 findFragmentByTag.如果 findFragmentByTag 的结果为 null,它只会调用 getItem.所以你不应该自己缓存这些片段.

The FragmentPagerAdapter already caches the Fragments for you. Each fragment is assigned a tag, and then the FragmentPagerAdapter tries to call findFragmentByTag. It only calls getItem if the result from findFragmentByTag is null. So you shouldn't have to cache the fragments yourself.

这篇关于在 fragmentpageradapter 中重用片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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