Fragment preloading in Android Development

During application development, an activity may be combined with multiple fragments using viewpagers (or other containers). If each fragment needs to load data, or load locally or from the network, it will need to initialize a large number of resources when the activity is first created. Of course, we will not be satisfied with such a result. So, can you initialize this fragment when you switch to it?

The answer is in the setuservisiblehint method in the fragment. Please see the API document about this method in fragment (domestic image address: http://zdz.la/YrpKlu ):

This method is used to tell the system whether the UI of this fragment is visible. Therefore, we only need to inherit the fragment and rewrite the method to load data when the fragment is visible, that is, lazy loading of the fragment.

The code is as follows:

In lazyfragment, I added three methods, one is onvisible, that is, when the fragment is set to be visible, and the other is oninvisable, that is, when the fragment is set to be invisible. In addition, an abstract method of lazyload is written, which is called in onvisible. You might think, why not call it directly in getuservisiblehint?

I write this for code reuse. Because in the fragment, we also need to create a view (oncreateview () method), and we may also need to perform other small initialization operations when it is not visible (such as initializing remote services that need to be called through Aidl). And setUserVisibleHint is called before onCreateView, so when the view is not initialized, it will be empty pointer exception when it is used in lazyLoad. If lazyload is separated into a method, its subclasses can do the following:

In the above class, we added a flag bit isprepared to indicate whether initialization is completed. Then we call after the initialization operation we need, for example, in the example above, after initializing view, set isPrepared to true and call lazyLoad () method. In lazyload (), if one of isprepared and isvisible is not true, it will not be executed. That is, the loading is continued only when the initialization is completed and visible, so as to avoid the problems caused by using before the initialization is completed.

Here I'll stop introducing the lazy loading implementation of fragment. If you are interested, you can explore it further, such as writing a fragment with the characteristics of slow initialization and refresh when visible.

The above is the fragment preloading problem in Android development introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message and Xiaobian will reply to you in time!

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
分享
二维码
< <上一篇
下一篇>>