我有一个viewpager通过代码的网页。我的 FragmentPagerAdapter
子会在的getItem
方法,这似乎浪费了一个新的片段。是否有一个 FragmentPagerAdapter
等同于 convertView
在 listAdapter
这使我重新使用已创建的片段?我的code是如下。
公共类ProfilePagerAdapter扩展FragmentPagerAdapter {
ArrayList的<简介> mProfiles =新的ArrayList<简介>();
公共ProfilePagerAdapter(FragmentManager FM){
超(FM);
}
/ **
*添加新的配置文件对象在该适配器被设置到寻呼机创建一个新的页面。
* @参数简介
* /
公共无效addProfile(资料简介){
mProfiles.add(资料);
}
@覆盖
公众诠释getCount将(){
返回mProfiles.size();
}
@覆盖
公共片段的getItem(INT位置){
返回新ProfileFragment(mProfiles.get(位置));
}
}
解决方案
在FragmentPagerAdapter已缓存的片段为您服务。每个片段分配一个标记,然后在FragmentPagerAdapter试图调用findFragmentByTag。它只要求的getItem如果从findFragmentByTag结果为空。所以,你不应该自己缓存片段。
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));
}
}
解决方案
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.