In Android development, we often encounter situations that control the display/concealment of a control based on a certain condition. Although setvisibility (int visibility) can do this, the hidden layout also executes the inflate () method when rendering, resulting in additional resource expenditure (memory), A better way to do this is to use the Viewstub object.
According to the official website, Viewstub is an invisible (invisible) View object that does not occupy any space (zero-sized) that can be used for time-lapse rendering. In the layout, we can set the layout parameters for him and specify the layouts file that you want to replace. When we call Viewstub's inflate () or setvisibility () method, Viewstub will be replaced with the specified layout, and the new view will inherit the viewstub layout parameters.
A simple example:
<viewstub android:id= "@+id/stub" android:inflatedid= "@+id/subtree" android:layout= "@layout/mysubtree " android:layout_width=" 120dip " android:layout_height=" 40dip "/>
Layout, Mysubtree is the view we want to render in time-lapse. After we call the inflate () method, the newly rendered view inherits the layout parameters of the viewstub, that is, the actual width of the Mysubtree layout will be 120DP and 40DP, respectively. The newly rendered view ID will be the subtree we specified (corresponding to the inflatedid= "@+id/subtree" in the above layout)
In fact, there is no need to call Findviewbyid (int), the official recommended practice is
Viewstub stub = (viewstub) Findviewbyid (r.id.stub); View inflated = stub.inflate ();
Inflated is our newly generated view object.
We can also bind the listener through Setinlfatelistener (Viewstub.oninflatelistener listener) to perform some action on the view with a callback when rendering is complete. (such as displaying specified data?) )
Android Viewstub time-lapse rendering application