I\'m trying to use Fragment with a ViewPager
using the FragmentPagerAdapter
.
What I\'m looking for to achieve is to replace a fragment, positioned
Here's my relatively simple solution to this problem. The keys to this solution are to use FragmentStatePagerAdapter
instead of FragmentPagerAdapter
as the former will remove unused fragments for you while the later still retains their instances. The second is the use of POSITION_NONE
in getItem(). I've used a simple List to keep track of my fragments. My requirement was to replace the entire list of fragments at once with a new list, but the below could be easily modified to replace individual fragments:
public class MyFragmentAdapter extends FragmentStatePagerAdapter {
private List fragmentList = new ArrayList();
private List tabTitleList = new ArrayList();
public MyFragmentAdapter(FragmentManager fm) {
super(fm);
}
public void addFragments(List fragments, List titles) {
fragmentList.clear();
tabTitleList.clear();
fragmentList.addAll(fragments);
tabTitleList.addAll(titles);
notifyDataSetChanged();
}
@Override
public int getItemPosition(Object object) {
if (fragmentList.contains(object)) {
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
@Override
public Fragment getItem(int item) {
if (item >= fragmentList.size()) {
return null;
}
return fragmentList.get(item);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitleList.get(position);
}
}