Reputation: 500
A ViewPager preloads fragments.
But with a pageWidth=0.5 (2 fragments per screen), I think it loads too much views before the current position...
I have
pageLimit=1
and pageWidth=0.5
.
It should be ok to preload LEFT1 and LEFT2, but why LEFT3 ?
LEFT3 is not on the next left screen...
I tried to understand ViewPager.java from support v4:
https://android.googlesource.com/platform/frameworks/support/+/support-library-27.1.1/core-ui/src/main/java/android/support/v4/view/ViewPager.java#1155
line 1155, it says
// Fill 3x the available width or up to the number of offscreen
// pages requested to either side, whichever is larger. But for multiple fragments per screen, it loads more before than current and after the current position.
With the Google sample project https://github.com/googlesamples/android-SlidingTabsBasic/
adding
protected void onCreate(Bundle savedInstanceState) {
[...]
mViewPager.setCurrentItem(25);
@Override
public float getPageWidth(int position) {
// 2 fragments per screen
return .5f;
}
@Override
public int getCount() {
// 50 fragments
return 50;
}
public Fragment getItem(int position) {
[...]
Log.d("debugpageviewer", "position="+position);
}
And it loads 7 fragments (3 before current position). The smaller the pageWidth, the more fragments are loaded before.
So, is this a bug or did I miss something ?
Upvotes: 1
Views: 479
Reputation: 370
You shall use ViewPager2
with FragmentStateAdapter
. See official explanation here:
Use ViewPager2 to slide between fragments: https://developer.android.com/develop/ui/views/animations/screen-slide-2
Migrate from ViewPager to ViewPager2: https://developer.android.com/develop/ui/views/animations/vp2-migration
Upvotes: 0
Reputation: 640
Try calling setOffscreenPageLimit()
on your ViewPager in your onCreate method.
For example mViewPager.setOffscreenPageLimit(2)
will make sure that no more than 3 fragments are always kept around: the current one and the two adjacent ones.
Upvotes: 1