Package article--fragment Lazy loading

Source: Internet
Author: User

Why do fragment lazy loading package??? A word "lazy"!!!
My boss told me: No lazy programmer is not a good chef ^~^ ^~^ ^~^

We may use Viewpager (or other containers) in combination with multiple fragment, believing that the used apes have met these questions:
1. When fragment is preloaded, that is, when an invisible fragment is loaded, the invisible fragment initialization data and pages may occupy a significant amount of resources;
2. If there is an animation on the page or if there are other persistent operations, the switching problem of the operation of the fragment state switch;
3. the problem of large code at initialization, yes, it seems to me that even the initialization is written
are inflater.inflate(R.layout.xxx,container,false) redundant and repetitive operations;

Now that we have a list of the issues we need to address, I'll start with the knowledge points that need to be learned, the encapsulation lifecycle, the common approach, and the advanced extension method, four points, about how I encapsulate

knowledge points to know

Yes, before encapsulation, you have to have a little bit more insight into the objects you want to encapsulate, or you can only elephant.

1. Fragment life cycle: At the very least, you need to know the ' created ', ' visible to the user ', ' go to ' background mode ', ' destroyed ' under the four actions it will go through what state. (Can view: http://www.cnblogs.com/purediy/p/3276545.html)
2. since it is lazy to load, we must know setuservisiblehint this method. (API Address: Http://androiddoc.qiniudn.com/reference/android/app/Fragment.html#setUserVisibleHint (Boolean));

Knowing how the life cycle works, let's do the next thing: encapsulate the life cycle of the fragment.

encapsulates the life cycle of lazy loading

We want to achieve the specific effect:
1. only light-weight initialization is done during preload;
2. The loading number is only started in the first visible state;
3. Breaking the life cycle into "visible" and "invisible" states;
4. make development more focused on the business itself, rather than on the tedious lifecycle of time delays;

We can probably pull out a few ways, such as:

initializing the XML, initializing the UI

    @Override     PublicViewOncreateview(Layoutinflater inflater, @Nullable viewgroup container, @Nullable Bundle savedinstancestate) {if(Getcontentviewlayoutid ()! =0) {returnInflater.inflate (Getcontentviewlayoutid (),NULL); }Else{return Super. Oncreateview (Inflater, container, savedinstancestate); }    }@Override     Public void onviewcreated(View view, @Nullable Bundle savedinstancestate) {Super. onviewcreated (view, savedinstancestate);    Initviewsandevents (view); }protected Abstract int Getcontentviewlayoutid();protected Abstract void initviewsandevents(view view);

If you use Dagger, Roboguice, butterknife These dependency injections, then initviewsandevents can do nothing

First visible state, visible state, first invisible State, invisible State

    Private BooleanIsfirstvisible =true;Private BooleanIsfirstinvisible =true;Private Booleanisprepared;@Override     Public void onactivitycreated(Bundle savedinstancestate) {Super. onactivitycreated (Savedinstancestate);    Initprepare (); }Private synchronized void Initprepare() {if(isprepared)        {onfirstuservisible (); }Else{isprepared =true; }    }@Override     Public void Setuservisiblehint(BooleanIsvisibletouser) {Super. Setuservisiblehint (Isvisibletouser);if(Isvisibletouser) {if(isfirstvisible) {isfirstvisible =false;            Initprepare (); }Else{onuservisible (); }        }Else{if(isfirstinvisible) {isfirstinvisible =false;            Onfirstuserinvisible (); }Else{onuserinvisible (); }        }    }protected Abstract void onfirstuservisible();protected Abstract void onuservisible();Private void onfirstuserinvisible() { }protected Abstract void onuserinvisible();

This way, you can use a sync lock when you're ready: synchronized

when destroying Fragment, you may need to do something like a ghost that unlocks the broadcast bindings, services, and so on:

    @Override    publicvoidonDestroy() {        DetoryViewAndThing();        super.onDestroy();    }    protectedabstractvoidDetoryViewAndThing();

Well, with the above basics, our Lazy load Prototype 1.0 is already ready to use, let's look at an example of use:

 Public  class imagefragment extends baselazyfragment{...@Override    protected int Getcontentviewlayoutid() {returnR.layout.fragment_images; }@Override    protected void onfirstuservisible() {//Load data/Turn on animation/broadcast ... ..}@Override    protected void onuservisible() {//Open animation/Broadcast ... ..}@Override    protected void onuserinvisible() {//Pause animation/pause broadcast .....}@Override    protected void initviewsandevents(View view) {//.........Mrecyclerview = (Recyclerview) View.findviewbyid (R.id.fragment_images_list_list_view); }//Do some destruction action    @Override    protected void detoryviewandthing() {if(NULL! = Mimageslistpresenter) {Mimageslistpresenter.detachview (); Mimageslistpresenter =NULL; }    }

Next we will encapsulate some common methods, such as page jump, toast, dialog Basic method ....

Public methods:


This paragraph is very good understanding, see the code can understand, no longer make too much explanation

protected void Readygo(Class<?> clazz) {Intent Intent =NewIntent (Getactivity (), clazz); StartActivity (intent);}protected void Readygo(class<?> Clazz, bundle bundle) {Intent Intent =NewIntent (Getactivity (), clazz);if(NULL! = bundle) {Intent.putextras (bundle); } startactivity (intent);}protected void Readygoforresult(Class<?> Clazz,intRequestcode) {Intent Intent =NewIntent (Getactivity (), clazz); Startactivityforresult (Intent, requestcode);}protected void Readygoforresult(Class<?> Clazz,intRequestcode, bundle bundle) {Intent Intent =NewIntent (Getactivity (), clazz);if(NULL! = bundle) {Intent.putextras (bundle); } startactivityforresult (Intent, requestcode);}protected void Showtoast(String msg) {if(NULL! = MSG &&! Stringutils.isempty (msg)) {Snackbar.make ((Activity) mcontext). GetWindow (). Getdecorview (), MSG, snackbar.length_sh    ORT). Show (); }}
Advanced Methods:

Unified Base Page encapsulation:

There are still some problems with page replacement (the UI level does not get darker when the normal page is restored from the error page/loading page, but the drawing level deepens, which is a bug.) )
But it is still for everyone to refer to this idea:

PrivateVaryviewhelpercontroller Mvaryviewhelpercontroller =NULL;//A Package view replacement method/** * Get the parent view you need to show * /protected AbstractViewGetloadingtargetview();/** * @param Toggle * *protected void toggleshowloading(BooleanToggle, String msg) {if(NULL= = Mvaryviewhelpercontroller) {Throw NewIllegalArgumentException ("You must return a right target view for loading"); }if(toggle)    {mvaryviewhelpercontroller.showloading (msg); }Else{Mvaryviewhelpercontroller.restore (); }}/** * Toggle Show Empty * * @param Toggle * *protected void Toggleshowempty(BooleanToggle, String msg, View.onclicklistener Onclicklistener) {if(NULL= = Mvaryviewhelpercontroller) {Throw NewIllegalArgumentException ("You must return a right target view for loading"); }if(toggle)    {Mvaryviewhelpercontroller.showempty (msg, onclicklistener); }Else{Mvaryviewhelpercontroller.restore (); }}/** * Toggle Show Error * * @param Toggle */protected void Toggleshowerror(BooleanToggle, String msg, View.onclicklistener Onclicklistener) {if(NULL= = Mvaryviewhelpercontroller) {Throw NewIllegalArgumentException ("You must return a right target view for loading"); }if(toggle)    {Mvaryviewhelpercontroller.showerror (msg, onclicklistener); }Else{Mvaryviewhelpercontroller.restore (); }}/** * Toggle Show Network Error * * @param Toggle */protected void Togglenetworkerror(BooleanToggle, View.onclicklistener Onclicklistener) {if(NULL= = Mvaryviewhelpercontroller) {Throw NewIllegalArgumentException ("You must return a right target view for loading"); }if(toggle)    {Mvaryviewhelpercontroller.shownetworkerror (Onclicklistener); }Else{Mvaryviewhelpercontroller.restore (); }}

Now a practical and easy lazy loading fragment is done ....

The description is relatively rough, follow-up will modify some wording and typesetting, please forgive us.
Happy April Fools ' Day to all!!!

Reprint please indicate the source:
http://blog.csdn.net/sinat_15877283/article/details/51037987;
This article is from: "Winledon's Blog"

Package article--fragment Lazy loading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.