I am currently trying to make framework for my future apps. I really like the ActionBar and the ViewPager, but miss a feature. I need to replace a Fragment/Tab in runtime.
Using the offical example, I would love to see something like a replaceTab(), but the Fragment itself isn't updated, no matter what I do.
You have to use a FragmentPagerAdapter to handle your fragment changes. There are 3 important things:
remove the previous fragment if it exists.
call notifyDataSetChanged() to refresh the list of pages.
return POSITION_NONE in getItemPosition if it's asking for an old fragment.
Here is the code I use with a Left and a Right page. I change dynamically the fragments depending on what the user does.
public class MyPager extends ViewPager {
private MyPagerAdapter mMyPagerAdapter;
public MyPager(Context context, FragmentActivity activity) {
super(context);
mMyPagerAdapter = new MyPagerAdapter(activity.getSupportFragmentManager());
setAdapter(mMyPagerAdapter);
}
public void replaceLeftFragment(Fragment fragment) {
mMyPagerAdapter.replaceLeftFragment(fragment);
}
public void replaceRightFragment(Fragment fragment) {
mMyPagerAdapter.replaceRightFragment(fragment);
}
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private FragmentManager mFragmentManager;
private Fragment mLeftFragment;
private Fragment mRightFragment;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
mFragmentManager = fm;
}
@Override
public Fragment getItem(int position) {
if (position == 0) {
return mLeftFragment;
} else {
return mRightFragment;
}
}
@Override
public int getCount() {
final int nbLeft = (mLeftFragment == null) ? 0 : 1;
final int nbRight = (mRightFragment == null) ? 0 : 1;
return (nbLeft + nbRight);
}
public void replaceLeftFragment(Fragment fragment) {
if (mLeftFragment != null) {
mFragmentManager.beginTransaction().remove(mLeftFragment).commit();
}
mLeftFragment = fragment;
notifyDataSetChanged();
}
public void replaceRightFragment(Fragment fragment) {
if (mRightFragment != null) {
mFragmentManager.beginTransaction().remove(mRightFragment).commit();
}
mRightFragment = fragment;
notifyDataSetChanged();
}
@Override
public int getItemPosition(Object object) {
if ((object!=mLeftFragment) && (object!=mRightFragment)) {
return POSITION_NONE;
}
return super.getItemPosition(object);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With