mewa
mewa

Reputation: 1552

Replacing ViewPager Fragments

I am trying to replace fragments from my ViewPager adapter but it does not seem to work. No errors do show either. When I'm calling the replace(int, Fragment) method it does nothing. Do you have any clue why it's nto working?

public class PagerAdapter extends FragmentPagerAdapter {
    private Vector<Fragment> mFragments;
    private Stack<Fragment> mHiddenFragments;
    public PagerAdapter(FragmentManager fm) {
        super(fm);
        mFragments = new Vector<Fragment>();
        mHiddenFragments = new Stack<Fragment>();
    }
// here is the replacement method I'm using
    public void replace(int index, Fragment fragment) { 
        mHiddenFragments.push(mFragments.get(index));
        mFragments.set(index, fragment);
        notifyDataSetChanged();
    }
    public void replace(int index) {
        mFragments.set(index, mHiddenFragments.pop());
        notifyDataSetChanged();
    }
    public void add(Fragment fragment) {
        mFragments.add(fragment);
        notifyDataSetChanged();
    public void remove(int index) {
        mFragments.remove(index);
        notifyDataSetChanged();
    }
}

EDIT: The part which I can't get to work is the removing of the fragment. It seems I can only remove fragments in the ViewPager that are after the one that's currently viewed.

example: Suppose I have fragments 0 & 1 => mFragments.size() == 2

mPagerAdapter.add(new GenreListFragment());
mPagerAdapter.remove(1);

Upvotes: 0

Views: 201

Answers (2)

mewa
mewa

Reputation: 1552

Okay, I finally know how to fix it. I changed my PagerAdapter to extend FragmentStatePagerAdapter instead of FragmentPagerAdapter and only then when I overrode getItemPosition started working properly and my fragments were replaced correctly.

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

Also I discovered that FragmentStatePagerAdapter will apparently be better in my case too (many dynamically created fragments).

Upvotes: 1

Junior Buckeridge
Junior Buckeridge

Reputation: 2085

My favorite solution is using nested fragments 'cause that gives me full control of them.

You could also check this Replace Fragment inside a ViewPager

Edit. You can also implement the abstract method of PagerAdapter for when you get a notifyDataSetChanged() call.

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

Regards.

Upvotes: 1

Related Questions