在 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.