How to prevent viewpager to initialize the next default view in android?

I have implemented a viewpager to show some implementation screens in an Android application. It has 4 different screens on which there are different animations. My problem is that when the user is on the 0 fragment of the viewpager, fragment 1 is initialized by default, and the animation ends in the background and when the user goes to fragment 1, then there is no animation (at the end of the animation, when fragment 1 is initialized simultaneously with the fragment 1). What I want to do is that when the user is on fragment 0, then only fragment 0 should initialize the next fragment, which is fragment 1. And when the user goes to fragment 1, then fragment 0 should be destroyed so that when canceling back to fragment 0, it should initialize the animation again. How can i do this.

+4
source share
2 answers

you can change the page memory limit of ViewPAger to

viewPager.setOffscreenPageLimit(0);

deafult is 1, so one fragment / view on the left and right will remain in memory.

BUT, but this is bad practice, viewPager supports one fragment / view on each side for better performance and smooth and immediate scrolling. I suggest you create a listener for ViewPagerthat starts the animation when scrolling to the desired fragment (without starting the animation in onCreateView). check ViewPager.OnPageChangeListener , especially the methodonPageSelected(int position)

edit: Google recognizes that parameter 0 for the restriction is weak, in the latest versions of logcat says:

Requested offscreen page limit 0 too small; defaulting to 1

, . , , , ( Google). ViewPager

public void setOffscreenPageLimit(int limit) {
    if (limit < DEFAULT_OFFSCREEN_PAGES) {
        Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " +
                DEFAULT_OFFSCREEN_PAGES);
        limit = DEFAULT_OFFSCREEN_PAGES;
    }
    if (limit != mOffscreenPageLimit) {
        mOffscreenPageLimit = limit;
        populate();
    }
}

ViewPager DEFAULT_OFFSCREEN_PAGES mOffscreenPageLimit populate();, Reflections, smth,

Field f = ViewPager.class.getDeclaredField("DEFAULT_OFFSCREEN_PAGES");
f.setAccessible(true);
f.setInt(viewPager, 0);

setOffscreenPageLimit(0);

0

Source: https://habr.com/ru/post/1568153/


All Articles