Explain the lazy loading of Android using fragment in viewpager

Let's look at the effect first:

First, we need to know what lazy loading is:

Lazy loading is to initialize the control first and load data when the user is visible.

Why lazy loading?

Lazy loading is mostly used in news and information clients. Imagine that if so many categories are loaded at once, it really consumes system resources. Some people may say that viewpager has a method of viewpager. Setoffsetscreenpagelimit(). Can't we just pass a 0 in? Those who have read the source code should know that even if you pass 0 in, the system will default to 1, that is, viewpager will still load a fragment before and after the current page.

We first write a base class for the fragment that needs lazy loading:

The comments have been written in detail. Next is the implementation of subclasses:

In this way, the lazy loading of fragment is basically completed. Another thing to note is that don't forget to write:

Here, I initialize all fragments when the activity is started. When printing the log, I will find that oncreateview() of each fragemnt has been executed, that is, after all the controls have been initialized, execute setuservisiblehint() when it is visible to the user to load the data.

There are many articles about lazy loading on the Internet, and there are also a variety of writing methods. Writing a suitable for yourself is the best.

->->->Click to download the source code<-<-<-

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>