I have a ViewPager2 with a FragmentStateAdapter and an offscreen page limit of 1:
viewPager.setAdapter(new MyFragmentStateAdapter(this));
viewPager.setOffscreenPageLimit(1);
public class MyFragmentStateAdapter extends FragmentStateAdapter {
MyFragmentStateAdapter(@NonNull Fragment fragment) {
super(fragment);
}
@NonNull
@Override
public Fragment createFragment(int position) {
return new ItemFragment(position);
}
@Override
public int getItemCount() {
return 15;
}
}
What happened:
- I observed that every time I swipe on the view pager there's a stutter in the swipe animation. So I started investigating.
What I discovered:
- I found out that new offscreen fragments in ViewPager2 are created at the beginning of the swipe gesture (while the now deprecated ViewPager created them at the end of the swipe gesture).
- It doesn't matter what the value of setOffscreenPageLimit is (except if your intention is to load all fragments at once). The problem happens every time the view pager needs to create a new offscreen fragment.
Why this is a problem:
- That means that the creation of fragments will always interfere with the swipe animation, basically defeating the purpose of setOffscreenPageLimit (however, if your fragments are very lightweight you may not notice the problem).
Question:
- Is there a way to force ViewPager2 with FragmentStateAdapter to create offscreen fragments at the end of the swipe animation (like the deprecated ViewPager did)?