How to clear view pager fragments

10,470

Solution 1

Had the same problem. For me it worked to override FragmentStatePagerAdapter

@Override
public Parcelable saveState() {
    return null;
}

@Override
public void restoreState(Parcelable state, ClassLoader loader) {

}

This work for me.

Solution 2

A simple way (not the best way) to do this is to override getItemPosition() in your PagerAdapter:

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

When the adapter's notifyDataSetChanged() method is called, the ViewPager will call getItemPosition() on the views it already knows about. By returning POSITION_NONE, you are telling the ViewPager to remove the view. Once the ViewPager removes the view, it will call getItem() to get an updated view.

So when the user returns back to Fragment A you would call:

viewPager.getAdapter().notifyDataSetChanged();

This will start the process of updating all your views.

Solution 3

You should use FragmentStatePagerAdapter instead of FragmentPagerAdapter!!!

Share:
10,470
visionix visionix
Author by

visionix visionix

Updated on June 17, 2022

Comments

  • visionix visionix
    visionix visionix almost 2 years

    I have a fragment A, in it I have a view pager with two fragment 1.1 and fragment 1.2 these fragments are children fragments of fragment A .

    Now when the user gets to Fragment B and then back to A I need to update the child fragments 1.1 and 1.2 by the options inside fragment B. The problem is I can`t update the fragments as they are already inside childfragment manager, also when I return back to fragment A getItem(int position) of the view pager not called. I managed to remove all the child fragments before I am setting the view pager adapter but I am not sure this it the right way to accomplish this functionality.

    I have 1.1 and 1.2 references inside Fragment A

    Thanks.