I\'ve got this activity, which holds a fragment. This fragment layout consists of a view pager with several fragments (two, actually).
When the view pager is created, it
My answer is kind of similar to Joshua Hunt's one, but by commiting the transaction in finishUpdate
method you get much better performance. One transaction instead of two per update.
Here is the code:
private class SuchPagerAdapter extends PagerAdapter{
private final FragmentManager mFragmentManager;
private SparseArray mFragments;
private FragmentTransaction mCurTransaction;
private SuchPagerAdapter(FragmentManager fragmentManager) {
mFragmentManager = fragmentManager;
mFragments = new SparseArray<>();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = getItem(position);
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
mCurTransaction.add(container.getId(),fragment,"fragment:"+position);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
mCurTransaction.detach(mFragments.get(position));
mFragments.remove(position);
}
@Override
public boolean isViewFromObject(View view, Object fragment) {
return ((Fragment) fragment).getView() == view;
}
public Fragment getItem(int position) {
return YoursVeryFragment.instantiate();
}
@Override
public void finishUpdate(ViewGroup container) {
if (mCurTransaction != null) {
mCurTransaction.commitAllowingStateLoss();
mCurTransaction = null;
mFragmentManager.executePendingTransactions();
}
}
@Override
public int getCount() {
return countOfPages;
}
}