Implementation of lazy loading of multiple fragments in Android imitation of today’s headlines

preface

Recently, I have time, so I have double Bodhisattva random Huang angry aluminum playing fragment lazy loading implementation. Although it is a small module, people who have done it have experience that it is usually not easy to succeed. It makes you toss and turn, sleepless all night and endless. I made a lazy loading function according to the style of today's headlines. Half of the article will explain the pit that you may encounter without loading data. Don't spoiler first.

Fragment life cycle review

GitHub code through train (local download)

Here is today's headline effect:

Self made effect, with pictures and truth:

Implementation idea:

Use the method setuservisiblehint() built in the fragment class to judge whether the current fragment is visible to the user, and make relevant logical judgment according to the isvisibletouser parameter of the callback. Override this method to create the variable isvisible to get the visible flag.

However, if the data is loaded directly according to isvisible judgment, the oncreateview() method may not be completed, and a null pointerexception null pointer exception will appear. Therefore, the data can be loaded only after the initialization of the control is completed and visible to the user.

Lazyloadfragment lazy loading fragment implementation:

Sub fragment loading data:

Finally, mainactivity Code:

Here comes the pit

Everyone said that it was OK to use setuservisiblehint () method, but they didn't say this problem. Did you use lazyloadfragment instead of loading data? Because you use viewpager, pageradapter, pageradapter, and interrupt debugging without calling setuservisiblehint(), isvisible is still false and lazload method is not executed. You need to call setuservisiblehint() with fragmentpageradapter display.

After changing to FragmentPagerAdapter, debug, call setUserVisibleHint, isVisible is ture.

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for 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
分享
二维码
< <上一篇
下一篇>>