Android Layoutinflater and Findviewbyid Source detailed

Source: Internet
Author: User

Layoutinflater Everyone is very familiar with the simple point is the layout file XML parser, Setcontentview function is also called Layoutinflater

Usage:
View view = Layoutinflater.from (this). Inflate (r.layout.activity_main, NULL);
Layoutinflater Lyinflater = (layoutinflater) getsystemservice (Context.layout_inflater_service);
The above usage is essentially the same.

Console Print Duplicate call Layoutinflater.from (this) the following instance of the same process is a singleton
[Email protected]
[Email protected]
[Email protected]

   First, Layoutinflater is an abstract class that instantiates objects that are taken out of service. But there is no instantiation of the object to the underlying binder. The final instance object is the Phonelayoutinflater class public    static Layoutinflater from (context context) {        Layoutinflater Layoutinflater = (layoutinflater) context.getsystemservice (context.layout_inflater_service);        if (Layoutinflater = = null) {            throw new Assertionerror ("Layoutinflater not Found.")        ;        return layoutinflater;    }

    Object Getsystemservice (String name) { if   if  (Minflater = = null  ) {Minflat Er  = layoutinflater.from (mbase). Cloneincontext (this ); //  instantiated in this place, primarily associated to Mbase context object instance     Minflater;     return   Mbase.getsystemservice (name); }

The     point is that the instantiation object of the context has a subclass Contextimpl.java inside registered    with the relevant servicepublic  Object Getsystemservice (String name) {        = system_service_map.get (name);         return NULL null : Fetcher.getservice (this);    }

System_service_map is a HASHMAP registered service that exists in this place and the object is cached. Private Static Finalhashmap<string, servicefetcher> system_service_map =NewHashmap<string, servicefetcher>(); Abstract Static classStaticservicefetcherextendsServicefetcher {PrivateObject mcachedinstance; @Override Public FinalObject GetService (Contextimpl unused) {synchronized(Staticservicefetcher. This) {Object service=mcachedinstance; if(Service! =NULL) {                    returnService; }                returnMcachedinstance =Createstaticservice (); }        }         Public AbstractObject Createstaticservice ();//This is used to create a static service} registerservice (Layout_inflater_service,NewServicefetcher () {//Create stand-alone objects for Layoutinflater         PublicObject CreateService (Contextimpl ctx) {returnPolicymanager.makenewlayoutinflater (Ctx.getoutercontext ()); }});

    /* Package*/ Static classServicefetcher {intMcontextcacheindex =-1; /*** Main entrypoint; only override if you don ' t need caching. */         PublicObject GetService (Contextimpl ctx) {//Contextimpl instance. Arraylist<object> cache =Ctx.mservicecache;            Object Service; synchronized(cache) {if(cache.size () = = 0) {                    //Initialize the cache vector on first access. //At this point snextpercontextservicecacheindex//is the number of potential services//cached Per-context.                     for(inti = 0; i < Snextpercontextservicecacheindex; i++) {Cache.Add (NULL); }                } Else{Service= Cache.get (Mcontextcacheindex);//gets whether the cache exists                    if(Service! =NULL) {                        returnService; }} Service= CreateService (CTX);//used to cache service instancesCache.set (mcontextcacheindex, service); returnService; }        }        /*** Override this to create a new Per-context instance of the * service.         GetService () would handle locking and caching. */         PublicObject CreateService (Contextimpl ctx) {Throw NewRuntimeException ("Not implemented"); }    }

Com.android.internal.policy.PolicyManager found the implementation class of Layoutinflater. This class is a proxy class, essentiallyPrivate Static FinalString policy_impl_class_name = "Com.android.internal.policy.impl.Policy"; Under the Policy\src\com\android\internal\policy\impl directory PublicLayoutinflater Makenewlayoutinflater (context context) {return NewPhonelayoutinflater (context);//instantiation of} policy\src\com\android\internal\policy\impl\phonelayoutinflater back to Layoutinflater recursive parsing XML using X Ml Pull Parser Parser PublicView Inflate (Xmlpullparser parser, ViewGroup root,Booleanattachtoroot) {        }

rinflate start recursion is XML parsingvoidRinflate (Xmlpullparser parser, View parent,FinalAttributeSet Attrs,BooleanFinishinflate)throwsxmlpullparserexception, IOException {Final intdepth =parser.getdepth (); inttype;  while((type = Parser.next ())! = Xmlpullparser.end_tag | |parser.getdepth ()> Depth) && type! =xmlpullparser.end_document) {            if(Type! =Xmlpullparser.start_tag) {                Continue; }            FinalString name =Parser.getname (); if(tag_request_focus.equals (name)) {Parserequestfocus (parser, parent); } Else if(tag_include.equals (name)) {if(parser.getdepth () = = 0) {                    Throw NewInflateexception ("<include/> cannot be the root element");            } parseinclude (parser, parent, attrs); } Else if(tag_merge.equals (name)) {Throw NewInflateexception ("<merge/> must be the root element"); } Else if(tag_1995.equals (name)) {FinalView view =Newblinklayout (Mcontext, attrs); FinalViewGroup ViewGroup =(viewgroup) parent; FinalViewgroup.layoutparams params =Viewgroup.generatelayoutparams (attrs); Rinflate (parser, view, Attrs,true);                            Viewgroup.addview (view, params); } Else {                FinalView view =Createviewfromtag (parent, name, Attrs); FinalViewGroup ViewGroup =(viewgroup) parent; FinalViewgroup.layoutparams params =Viewgroup.generatelayoutparams (attrs); Rinflate (parser, view, Attrs,true);            Viewgroup.addview (view, params); }        }        if(finishinflate) parent.onfinishinflate ();//Parse it out, we can customize this method to make a copy of the information that can be removed from the child view}

basically the layout is viewgroup of the child class inside have the children view, our common Findviewbyid is to traverse to find the corresponding ID of the view Public FinalView Findviewbyid (intID) {if(ID < 0) {            return NULL; }        returnfindviewtraversal (ID); Look directly at the findviewtraversal in ViewGroup @OverrideprotectedView Findviewtraversal (intID) {if(id = = MID) {//equals oneself            return  This; }        FinalView[] where =Mchildren; Final intLen =Mchildrencount;  for(inti = 0; i < Len; i++) {View v=Where[i]; if((V.mprivateflags & is_root_namespace) = = 0) {//is_root_namespace may be a query to the last level (guess) and then traverse the queryv =V.findviewbyid (ID); if(V! =NULL) {                    returnv; }            }        }        return NULL; }

If the layout hierarchy is too deep to parse the XML and the lookup view is CPU-intensive, it is necessary to do the layout optimization during the project.

This article source code: 4.1

Android Layoutinflater and Findviewbyid Source detailed

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.