user6741232 user6741232 - 3 months ago 44
Android Question

How to disable preloading next page in a ViewPager?

How can I disable the preloading in a

ViewPager
?

I have a ViewPager with 3 pages. So I don't want to load the next page and previous page. How can I disable this behaviour?

I tried


viewPager.setOffscreenPageLimit(1)


But this is not working.

Answer

As doc says:

This is offered as an optimization. If you know in advance the number of pages you will need to support or have lazy-loading mechanisms in place on your pages, tweaking this setting can have benefits in perceived smoothness of paging animations and interaction. If you have a small number of pages (3-4) that you can keep active all at once, less time will be spent in layout for newly created view subtrees as the user pages back and forth.

So following code is not work as you expected:

viewPager.setOffscreenPageLimit(1) 

But there is a trick, You can initilize view|value just when fragment is visible to user with:

 @Override
    public void setMenuVisibility(final boolean visible) {
        super.setMenuVisibility(visible);
        if (visible) {
            // do something nice here
        }
    }