PagerAdapter.notifyDataSetChanged does not refresh fragments

royB picture royB · Jan 23, 2015 · Viewed 31.3k times · Source

My Activity contains a ViewPager and it's custom Adapter which extends FragmentStatePagerAdapter. ViewPager contains 3 fragments

Code to remove Fragments from the ViewPager

MainActivity

public void deleteElement(){
    final int currentItem = mViewPager.getCurrentItem();
    mPagerAdapter.removeItem(currentItem);
    mPagerAdapter.notifyDataSetChanged();
}

CustomPagerAdapter

private ArrayList<Item> data;
public void removeItem(int index){
        data.remove(index);
}

when removing the middle Fragment (index 1):

  • from data i'm removing the correct item.
  • Problem is that i (i guess) Fragment 3 is removed after notifyDataSetChanged and the current Fragment is still the fragment that the user saw and the data that is being loaded is from the SavedInstance bundle

So the end result that the user still see the same Fragment that he tried to remove which is kinda suck for him.

Ideas?

***** EDIT ******

seems like ViewPager2 Features might solve this issue and many other issues as well

Answer

kelvincer picture kelvincer · Jan 23, 2015

Try adding this:

private class MyPagerAdapter extends FragmentStatePagerAdapter {

//... your existing code

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

}