In the project, it is unavoidable to encounter this kind of demand, when the program runs, it is necessary to dynamically decide which view or layout to display according to the condition, the most common idea is to write the view that needs to be dynamically displayed first in the layout. Then set their visibility to view.gone, and finally change its visibility dynamically by controlling view.visiable in the code. The advantage of this approach is that logic is simple and control is more flexible. However, its disadvantage is that it consumes resources, Although the view is initially visible view.gone but in the inflate layout, the view will still be inflate, that is, the object will still be created, instantiated, and set properties. In other words, it consumes resources such as memory.
The recommended practice is to use android.view.viewstub,viewstub as a lightweight view that is very simple to use:
Mviewstub = (viewstub) This.findviewbyid (r.id.viewstub);
Mviewstub.inflate ();
It is an invisible, non-occupying layout location that occupies a very small resource and is equivalent to a placeholder control. When used, you can specify a layout for viewstub, when the inflate layout, only viewstub is initialized, and then when Viewstub is set to visible or when viewstub.inflate () is called, the The layout that viewstub points to is instantiated by inflate, and this layout file replaces the current viewstub directly, and then viewstub the layout properties (layout_margin***, Layout_ width, etc.) will be passed to the layout it points to . In this way, you can use Viewstub to dynamically display layouts at run time, saving memory resources.
The following we see from the Viewstub source code inflate () method implementation principle:
<span style= "color: #333333;" > Public View Inflate () {final viewparent viewparent = GetParent (); if (viewparent! = null && viewparent instanceof ViewGroup) {if (Mlayoutresource! = 0) { Final ViewGroup parent = (viewgroup) viewparent; Final Layoutinflater factory; if (minflater! = null) {factory = Minflater; } else {factory = Layoutinflater.from (Mcontext); Final View view = Factory.inflate (Mlayoutresource, parent, false); if (minflatedid! = no_id) {View.setid (minflatedid); } Final int index = Parent.indexofchild (this); </span><span style= "color: #cc0000;" >parent.removeviewinlayout (this); </span><span style= "color: #333333;" > Final Viewgroup.layoutparams layoutparams = GetlayoutparaMS (); if (layoutparams! = null) {Parent.addview (view, index, layoutparams); } else {Parent.addview (view, index); } minflatedviewref = new weakreference<view> (View); if (Minflatelistener! = null) {Minflatelistener.oninflate (this, view); } return view; } else {throw new IllegalArgumentException ("Viewstub must has a valid Layoutresource"); }} else {throw new IllegalStateException ("Viewstub must has a non-null viewgroup viewparent"); }}</span>let's start by looking at the entrance to the method:
1, in line 2nd, the first is to get viewstub its parent view object.
2, and then at the beginning of the 4th line must be able to enter the judgment, Mlayoutresource is the need to inflate layout resources, and then fill in the 13th row of this layout resources.
3, then in the 21st line, important to come, parent.removeviewinlayout (this); What does this code mean? See the method name to know, this is the Viewstub object, meaning that the current Viewstub object is removed from the parent view.
4, then the 23rd to 28th Line, is to get viewstub layoutparams layout Parameter object, if it exists, assign it to the inflate layout object, and then add the inflate layout object to the parent view.
5. Finally, return the layout object of inflate.
OK, the source parsing is complete!!!
From the above, when we call the Viewstub.inflate () method The second time, because the Viewstub object has been removed, in line 2nd, 4, the resulting viewparent is null, At this point, we'll go. Else throws a IllegalStateException exception:viewstub must has a non-null viewgroup viewparent.
A few things to note:
1.ViewStub is often referred to as "lazy loading," because in most cases, the program does not need to display the layout file pointed to by Viewstub, only under certain few conditions, the layout file pointed at this time viewstub need to be inflate, This layout file replaces the current viewstub directly, either through Viewstub.infalte () or viewstub.setvisibility (view.visible).
2. It is important to have a proper grasp of the viewstub application scenario, because using viewstub can optimize the layout and generally apply to the current layout or control in less user-friendly situations, which improves performance, saves memory, and accelerates interface rendering.
3. The inflate operation on the viewstub can only be performed once, because the inflate is to instantiate the layout it points to and replace the current viewstub itself (thus reflecting the viewstub "placeholder" nature), once replaced, There is no viewstub control in the original layout file, so if you infalte the viewstub multiple times, an error message appears: Viewstub must has a non-null viewgroup viewparent.
In 4.3, the viewstub points to the layout file resolution inflate and replace the current viewstub itself, not the full meaning of the replacement (and the include tag is not the same), replace the layout of the file is viewstub the params , the other layout properties are based on the layout file itself.
5.viewstub itself is not visible, viewstub.setvisibility (int visibility) is not the same as other view controls, we can see from the source point of view viewstub.setvisibility () Method of action:
This method means Viewstub's setvisibility () Set to view.visible or invisible if it is first used, it will automatically inflate the layout file it points to and replace the viewstub itself, which is equivalent to setting the visibility of the layout file to which it points .
Well, the principle is so much, to see how the code is implemented:
First Look at:
Using the Activity_main.xml of the viewstub:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " android:orientation= "vertical" tools:context= "com.example.viewstub.MainActivity" > <switch android:id= "@+id/switch1" android:layout_width= "wrap_content" android:layout_height= "wrap_content "/> <viewstub android:id=" @+id/viewstub " android:layout_width=" Match_parent " android: layout_height= "Match_parent" android:layout_marginbottom= "10DP" android:layout_marginleft= "10DP" android:layout_marginright= "10DP" android:layout_margintop= "10DP" android:layout= "@layout/hide _layout "/></linearlayout>
Hide_layout.xml
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" match_parent " android:layout_height=" Match_parent " android: Background= "#00ffff" android:orientation= "vertical" > <button android:id= "@+id/hide_layout_ BTN " android:layout_width=" wrap_content " android:layout_height=" wrap_content " android:layout_ gravity= "center" android:text= "click Me"/></linearlayout>
Code files:
public class Mainactivity extends Actionbaractivity {private viewstub mviewstub;private Switch Mswitch;private boolean fl AG = false; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); mviewstub = (viewstub) This.findviewbyid (r.id.viewstub);// Instantiate Viewstubmswitch = (Switch) Findviewbyid (R.ID.SWITCH1); Mswitch.setoncheckedchangelistener (new Oncheckedchangelistener () {@Overridepublic void oncheckedchanged (Compoundbutton buttonview,boolean isChecked) {if ( isChecked) {if (!flag) {mviewstub.inflate ();//viewstub can only be inflate once, returning a view object that fills the resource//mviewstub.setvisibility ( view.visible);) flag = true;} Else{mviewstub.setvisibility (view.visible);} Button MBtn = (button) Findviewbyid (R.ID.HIDE_LAYOUT_BTN),//viewstub the control inside the replaced layout mbtn.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {toast.maketext (Getapplicationcontext (), "Click me!", Toast.length_short). Show ();}}); else {mviewstub.setvisibility (view.go(NE);}}});}}
Note: Use Viewstub to replace the control in the layout, direct Findviewbyid can be.
Finally, let's expand on several other tags that are commonly used in layout optimization:
1. Layout Reuse <include/> can load external XML directly into the current structure via this tag, which is a common label for reusing UI resources.
<include/> Tags can reuse layout files, simple to use as follows:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " android:orientation= "vertical" tools:context= "com.example.viewstub.MainActivity" > <switch android:id= "@+id/switch1" android:layout_width= "wrap_content" android:layout_height= "wrap_content "/> <include layout=" @layout/include_layout "/></linearlayout>
use the controls in the layout file in the Include tab to Findviewbyid directly.
2. Reduce the view level <merge/>
The <merge/> Tag plays a very important role in the structural optimization of the UI, which can be used to prune unnecessary layers and optimize the UI. <merge/> is used to replace the framelayout (because all activity views have a framelayout root node, and if the current layout root node is framelayout, You can use merge instead to reduce redundant levels ) or when one layout contains another, the <merge/> tab eliminates the extra view groups in the view hierarchy . For example, your main layout file is a vertical layout, and include introduces a vertical layout, which is meaningless if the linearlayout used by the include layout makes sense, and instead slows down your UI rendering. This can be optimized using the <merge/> tag.
<merge xmlns:android= "Http://schemas.android.com/apk/res/android" > <button android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content" android:text= ""/> <textview Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= ""/></ Merge>
Reprint please specify the source--http://blog.csdn.net/u010687392
Android Layout performance optimization-Viewstub lazy loading technology from the source point of view