shellshy
shellshy

Reputation: 23

Viewpager Lazy load data

ViewPager has a public function setOffscreenPageLimit (http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int)), What is it? Here is the description from the doc:

Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.(I had test it,the min params about the function is 1,althought I set it to 0,It work as well as 0)

How about my demo

Now,my demo contains a viewpager with 6 fragment in it.When it run,the viewpager will load the first pager and the second pager,but it only show the first pager on the screen,When we move to the second pager,It will load the third pager.All these is easy to understand.

show the situation about the first pager load

From the picture we can know the pager 2 had loaded when the app show pager 1,so we can move pager to pager2 and does no need to load the data on pager 2 again.

When i move it to pager 3 continue,Pager 1 will go into stop status,and pager 4 will be loading.

pager1-> pager2 -> pager3 -> pager4

stop -> resume but not show -> resume and show -> resume but not show

Here is the picture to show what is happend about above!

pager3 in show statsu,pager1 in stop status,and pager2,pager4 in resume but not show

What I need my app do!

I just want the viewpager load the data which pager is showing now.For example,When the app first run,It only init the pager1 and load what the data need in pager1. Pager2 will not load data.

Here is my demo:https://github.com/shellshy/LazyViewPager

Upvotes: 0

Views: 5839

Answers (3)

AnswerZhao
AnswerZhao

Reputation: 376

Just like this.

public class FragmentSample extends Fragment{
    ...  
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
           // load you data
        }
    }
    ...
}

Upvotes: 2

Jeffery Ma
Jeffery Ma

Reputation: 3341

Lazy load data for ViewPager Items

maybe you can see my answer which use setUserVisibleHint() to customer a fragment

Upvotes: 0

sverma
sverma

Reputation: 39

setOffscreenPageLimit() is normally, we use to set limit of pages that will set in idle state. this method we use when you have a long list of pages in view pager. this method keep away to occurred low memory error and also beneficial when you set lazy loading on pager.

Upvotes: 0

Related Questions