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;
}