Android Viewpager how to dynamically remove a Fragment?

Edmund Rojas picture Edmund Rojas · Aug 27, 2013 · Viewed 7.1k times · Source

I have been struggling a few days with building functionality in my application that allows a user to remove a page/Fragment from a Viewpager, I have tried changing my FragmentPageAdapter to a FragmentStatePageAdapter and override my getItemPosition() to return POSITION_NONE; however this still does not allow me to remove the Fragment dynamically when I call fragments.remove(page);

pageAdapter.notifyDataSetChanged();

has anyone done this successfully before? seems like it should be really simple but it hasnt been, below is my fragment adapter, any help would go a long way thanks!

class MyPageAdapter extends FragmentStatePagerAdapter {

    private List<Fragment> fragments;

    public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {

        super(fm);

        this.fragments = fragments;

    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public Fragment getItem(int position) {

        return this.fragments.get(position);

    }

    @Override
    public float getPageWidth(int position) {

        if (position == 0) {
            return (0.75f);
        } else {
            return (1f);
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {

        MyFragment theFragment = (MyFragment) this.fragments.get(position);

        return theFragment.returnTitle();

    }

    @Override
    public int getCount() {

        return this.fragments.size();

    }

}

Answer

keybee picture keybee · Aug 27, 2013

Use Jake Wharton's ViewPagerIndicator. It also has an open source sample application with this funcionality (add and remove fragments from options menu).

Put this into you adapter:

public void setCount(int count) {
    if (count > 0 && count <= 10) {
        mCount = count;
        notifyDataSetChanged();
    }
}

And this is adding a page:

    if (mAdapter.getCount() < 10) {
        mAdapter.setCount(mAdapter.getCount() + 1);
        mIndicator.notifyDataSetChanged();
    }

This is how to remove a page:

if (mAdapter.getCount() > 1) {
                mAdapter.setCount(mAdapter.getCount() - 1);
                mIndicator.notifyDataSetChanged();
            }