Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a Fragment/Tab in a Viewpager

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.

like image 398
user1014917 Avatar asked Apr 02 '12 17:04

user1014917


1 Answers

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);
    }

}
like image 198
Arnaud SmartFun Avatar answered Nov 15 '22 06:11

Arnaud SmartFun