0

I am using ViewPager2 with FragmentStateAdapter and if I have three fragments the default behavior is to save fragment state, actually I have one fragment but create instances and pass different types to it, so if I have Fragment A, A1 and A2 and I scroll from a1 to a then back to a the adapter doesn't recreate A but use an old instance of A and that's what is happening to me

But instead, I don't want that behaviour I want the adapter to create a new instance of fragment A instead of using the last instance and then if I scroll to B create a new instance of B and don't use the last instance.

public class JobsViewPagerAdapter extends FragmentStateAdapter {


private List<Integer> fragmentsType = new ArrayList<Integer>(){{
    add(JobsType.Booked.numValue);
    add(JobsType.INVITED.numValue);
    add(JobsType.PAST.numValue);
}};

public JobsViewPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
    super(fragmentActivity);
}


@NonNull
@Override
public Fragment createFragment(int position) {
    return JobsInnerFragment.newInstance(fragmentsType.get(position));
}

@Override
public int getItemCount() {
    return fragmentsType.size();
}


public enum JobsType {
    Booked(0), TODAY(1), INVITED(2), UPCOMING(3), PAST(4);

    private int numValue;

    JobsType(int value) {
        this.numValue = value;
    }

    public int getNumValue() {
        return numValue;
    }
}

}

 public static JobsInnerFragment newInstance(int jobsType){
    JobsInnerFragment jobFragment = new JobsInnerFragment();
    Bundle todayJobsBundle = new Bundle();
    todayJobsBundle.putInt(Constants.JOBS_TYPE, jobsType);
    jobFragment.setArguments(todayJobsBundle);
    return jobFragment;
}
Emmanuel .C
  • 298
  • 2
  • 6
Karim Ata
  • 343
  • 6
  • 15

1 Answers1

4

Try setting offscreenPageLimit to ViewPager as 1

viewPager2.offscreenPageLimit=1

From documentation

Set the number of pages that should be retained to either side of the currently visible page(s). Pages beyond this limit will be recreated from the adapter when needed

https://developer.android.com/reference/androidx/viewpager2/widget/ViewPager2#setOffscreenPageLimit(int)

Manohar
  • 22,116
  • 9
  • 108
  • 144