We all know that fragment put in Viewpager inside, Viewpager will help us preload one, but when we want to see the contents of fragment, we may only go to see the first one, not to see the second one, If this is not to implement fragment lazy loading, it will be redundant to load some data, causing users to consume more traffic, so we take lazy loading way.
The so-called lazy loading is when fragment is completely visible, we load the data again.
We know that when we go sliding, fragment will show and hide, and fragment will call a method when fragment is fully displayed in front of us.
Directly below the code
First, we define an abstract class to inherit our fragment,
1 Packagefragment;2 3 Importandroid.support.v4.app.Fragment;4 5 /**6 * Fragment Lazy loading7 */8 Public Abstract classLazyfragmentextendsfragment{9 Ten protected BooleanisVisible; One A @Override - Public voidSetuservisiblehint (BooleanIsvisibletouser) {//The method is called when the frahment is completely visible from sight - Super. Setuservisiblehint (isvisibletouser); the if(Getuservisiblehint ()) { -IsVisible =true; - onvisible (); -}Else { +IsVisible =false; - oninvisible (); + } A } at - protected Abstract voidLazyload ();//lazy Loading method, in which we add data for each component of fragment - - protected voidonvisible () { - lazyload (); - } in - protected voidoninvisible () { to + } - the}
In fact, we can also in our fragment directly to write these operations, but written in abstract class can be very convenient for us to reuse, reduce work.
Public classFragmentextendslazyfragment {Private Booleanisprepared;//flag bit, the flag has been initialized to complete. //in this method, we'll add data to our fragment.@Overrideprotected voidlazyload () {if(Isprepared &&isVisible) {getnewsdate (Getactivity (), channelid); Page++; Isprepared=false; }} @Override PublicView Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View View= Layoutinflater.from (Getactivity ()). Inflate (R.layout.fragment, container,false); Isprepared=true; Lazyload ();//Here we call to go down and load our data returnview; }
Here is the sequence of calls for the life cycle method of fragment, which you can use to print out a log.
Lazy Loading of android--fragment