I want to use ViewStub in android, so please help me. I have created
ViewStub stub = new ViewStub;
View inflated = stub.inflate();
How to use it programmatically?
I want to use ViewStub in android, so please help me. I have created
ViewStub stub = new ViewStub;
View inflated = stub.inflate();
How to use it programmatically?
Here is an example for show/hide and change data of
ViewStub
at run timeactivity_main.xml
layout_of_view_stub.xml
MainActivity.java
Simply a ViewStub is used to increase efficiency of rendering layout. By using ViewStub, manually views can be created but not added to view hierarchy. At the runtime, can be easily inflated, while ViewStub is inflated, the content of the viewstub will be replaced the defined layout in the viewstub.
activity_main.xml we defined viewstub but not created first.
Simple example gives better understanding,
At runtime, when we inflate, the content will be replaced with the layout defined in the viewstub.
So, Lets look at again the view hierarchy,
when we inflate the viewstub, it will be removed from the view hierarchy.
Like the documentation says,
ViewStub
is aView
that is inflated lazily.You can declare a
ViewStub
in an XML file like this:The
android:layout
attribute is a reference to theView
that will be inflated next to a call ofinflate()
. SoWhen the method
inflate()
is invoked theViewStub
is removed from its parent and replaced with the rightView
(the root view ofmySubTree
layout).If you want to do this progammatically then your code should be something like: