Overview
The application of Layoutinflater in Android development is very common, you can instantiate the XML layout file under res/layout/as a control of view or ViewGroup. Similar to Findviewbyid, but Findviewbyid looks for a specific control in an XML layout file, which is not exactly the same.
Application Scenarios:
1. In an interface that is not loaded or wants to be loaded dynamically, you need to use Layoutinflater.inflate () to load the layout file;
2. For an already loaded interface, you can use the Findviewbyid method to obtain the interface elements;
Three ways to achieve Layoutinflater objects
1.LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);2.LayoutInflater layoutInflater = getLayoutInflater();3.LayoutInflater layoutInflater = LayoutInflater.from(context);
However, the essence of the above three kinds of layoutinflater is the same, and ultimately it is called the first way to generate the Layoutinflater object, we can view the source code:
Source code for Getlayoutinflater ():
The Getlayoutinflater () method of activity is to call Phonewindow's Getlayoutinflater () method, the source code is as follows:
publicPhoneWindow(Context context) { super(context); mLayoutInflater = LayoutInflater.from(context); }
Source code for Layoutinflater.from (context):
/** * Obtains the LayoutInflater from the given context. */ publicstaticfrom(Context context) { LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); ifnull) { thrownew AssertionError("LayoutInflater not found."); } return LayoutInflater; }
It can be seen that it is also called Context.getsystemservice (). Once you get the Layoutinflater object, you can call its inflate () method to load the layout.
Inflate method
The inflate method is based on the passing of different parameters, a total of four methods, as follows:
public View inflate (int resource, ViewGroup root) public View inflate (int resource, ViewGroup root, boolean attachtoroot) public View inflate (Xmlpullparser parser, ViewGroup root) public View inflate (Xmlpullparser parser, ViewGroup root, Boolean attachtoroot)
Here we mainly use the previous two methods.
Let's analyze the first method public View inflate (int resource, ViewGroup root):
The first parameter represents the layout ID to be loaded, and the second parameter represents a nested parent layout for the loaded layout, and null if not required.
The second method of public View inflate (int resource, ViewGroup root, Boolean attachtoroot):
The first two parameters are consistent with the method above, and the third parameter, Attachtoroot, indicates whether to add the loaded layout to root.
From the above inflate (LayoutID, null) and inflate (R.layout.button, root,false) effects seem to be the same, in fact the effect of the two methods is completely different.
code example
Layout file Button.xml:
<?xml version="1.0" encoding="utf-8"?><Button xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="100dp" android:text="button" ></Button>
Code in activity:
publicclass MainActivity extends Activity { @Override protectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);// setContentView(R.layout.activity_other); ViewGroup group = (ViewGroup) findViewById(android.R.id.content); LayoutInflater layoutInflater = getLayoutInflater(); null); group.addView(view); }}
As follows:
To modify the code in the activity:
publicclass MainActivity extends Activity { @Override protectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);// setContentView(R.layout.activity_other); ViewGroup group = (ViewGroup) findViewById(android.R.id.content); LayoutInflater layoutInflater = getLayoutInflater(); View view = layoutInflater.inflate(R.layout.button, group,false); group.addView(view); }}
After running,:
Continue to modify the code in activity:
public class mainactivity extends activity { @Override protected void oncreate (Bundle savedinstancestate) {super . OnCreate (savedinstancestate); //Setcontentview (r.layout.activity_other); ViewGroup Group = (viewgroup) Findviewbyid (Android. R.id.content); Layoutinflater layoutinflater = Getlayoutinflater (); View view = Layoutinflater.inflate (R.layout.button, Group,true ); Group.addview (view); }}
After running, the discovery throws exception information:
E/androidruntime (3362): caused by:java.lang.IllegalStateException:The specified child already have a parent. You must call Removeview () on the child ' s parent first.
The above mainly uses three different inflate methods:
1.inflate (R.layout.button, NULL);
2.inflate (R.layout.button, Group,false);
3.inflate (R.layout.button, group,true);
From the above three different results, you can see that when using inflate (LayoutID, NULL), the setting of the width height property in the layout is invalid, but when using inflate (R.layout.button, Root,false), The wide and high attributes in the layout have also played a role. When using inflate (LayoutID, Root, True), an exception is thrown and will not function properly.
Why does this result? We can see the reason through the source code.
SOURCE parsing
We enter the inflate method to view:
publicinflate(intboolean attachToRoot) { final Resources res = getContext().getResources(); final XmlResourceParser parser = res.getLayout(resource); try { return inflate(parser, root, attachToRoot); finally { parser.close(); } }
Discover the above three ways, and ultimately call inflate (parser, root, Attachtoroot) method, continue to enter:
PublicViewInflate(Xmlpullparser parser, ViewGroup root,BooleanAttachtoroot) {synchronized(Mconstructorargs) {Trace.tracebegin (Trace.trace_tag_view,"Inflate");FinalAttributeSet attrs = xml.asattributeset (parser); Context Lastcontext = (context) mconstructorargs[0]; mconstructorargs[0] = Mcontext; View result = root;Try{//Look for the root node. intType while((type = Parser.next ())! = Xmlpullparser.start_tag && Type! = xmlpullparser.end_document) {//Empty}if(Type! = Xmlpullparser.start_tag) {Throw NewInflateexception (parser.getpositiondescription () +": No start tag found!"); }FinalString name = Parser.getname ();if(tag_merge.equals (name)) {if(Root = =NULL|| !attachtoroot) {Throw NewInflateexception ("<merge/> can be used only with a valid"+"ViewGroup Root and Attachtoroot=true"); } rinflate (parser, root, Attrs,false,false); }Else{//Temp is the root view and was found in the XML FinalView temp = Createviewfromtag (root, Name, Attrs,false); Viewgroup.layoutparams params =NULL;if(Root! =NULL) {//Create layout params that match root, if suppliedparams = Root.generatelayoutparams (attrs);if(!attachtoroot) {//Set the layout params for temp If we is not //attaching. (If We is, we use AddView, below)Temp.setlayoutparams (params); } }//Inflate all children under tempRinflate (parser, temp, attrs,true,true);//We is supposed to attach all the views We found (int temp) //to root. do it now. if(Root! =NULL&& attachtoroot) {Root.addview (temp, params); }//Decide whether to return the root is passed in or the //Top view found in XML. if(Root = =NULL|| !attachtoroot) {result = temp; } } }Catch(Xmlpullparserexception e) {Inflateexception ex =NewInflateexception (E.getmessage ()); Ex.initcause (e);ThrowEx }Catch(IOException e) {Inflateexception ex =NewInflateexception (parser.getpositiondescription () +": "+ e.getmessage ()); Ex.initcause (e);ThrowEx }finally{//Don ' t retain static reference on context.mconstructorargs[0] = Lastcontext; mconstructorargs[1] =NULL; } trace.traceend (Trace.trace_tag_view);returnResult } }
In the above code, delete a debug part, you can see the key code:
1.View result = root, the parameter root is assigned to the result, and when the method ends, the result is returned.
2. The following final view temp = Createviewfromtag (root, Name, Attrs, false); Create a View;
3. Then:
if (root! = NULL) {//create layout params that match root, if supplied params = root.generatelayoutparams (attrs); if (!attachtoroot) {//set the layout par AMS for temp if we is not //attaching. (if we are , we use AddView, below) t Emp.setlayoutparams (params); } }
If root is not empty and Attachtoroot = False, set Setlayoutparams to temp, which explains the use of inflate (R.layout.button, Group,false) in the code above, The width and height of the layout can take effect.
4. Then look at the following:
ifnull && attachToRoot) { params);}
If root is not empty and Attachtoroot is true, then params = = null. From here, we can see why the inflate (R.layout.button, group,true) will throw exception information, because the operation of the Root.addview (temp, params) has been performed inside the method, Outside the code that executes Group.addview (view), an exception is thrown. To solve this problem, just remove the Group.addview (view) code.
5. Continue:
ifnull || !attachToRoot) { result = temp;}
You can see that when root equals null, or Attachtoroot is false, the TEMP is assigned to result directly. From here we can see that when we execute code inflate (R.layout.button, NULL), it is actually executed inflate (R.layout.button, Null,false), Result is not set setlayoutparams, so the width height property set in the layout is not valid.
Summarize
Inflate (LayoutID, NULL), the setting of the width height property in the layout is invalid;
Inflate (R.layout.button, Root,false), the width and Height properties in the layout are valid;
Inflate (LayoutID, root, true) does not need to perform a addview operation at the back, otherwise an exception is reported.
The parsing of the above methods for layoutinflater.inflate is over.
Analysis of layoutinflater principle in Android