Important Methods
First, let us get the reference of ViewStub
ViewStub in XML
<ViewStub android:id="@+id/viewStubToLearn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:inflatedId="@+id/inflatedviewsub" android:layout="@layout/custom_viewstub" />
Syntax:
// viewStubToLearn is the id of ViewStub defined in xml ViewStub simpleViewStub = ((ViewStub) findViewById(R.id.viewStubToLearn));
Methods |
Description |
---|---|
getInflatedId() | To get the id taken by the inflated view |
setLayoutResource(int layoutResource) | Via this method, we can set the layout resource to inflate when StubbedView becomes visible or invisible or when inflate() is invoked. |
getLayoutResource() | To get the layout resource that will be used by setVisibility(int) or inflate() to replace this StubbedView in its present with another view. The resultant will be an integer value |
inflate() | In order to Inflate the layout resource that gets identified by getLayoutResource() and replace this StubbedView in its parent by the inflated layout resource. |
setVisibility(int visibility) | Sometimes there is a need to make the visibility to invisible and later on visible. |
setOnInflateListener(OnInflateListenerinflateListener) | Via this call, It specifies the inflate listener to be notified after this ViewStub successfully inflated its layout resource. |
ViewStub in Android with Example
In Android, ViewStub is a zero-sized invisible View and very flexible in that we can lazily inflate layout resources at runtime. It is a dumb and lightweight view and it has zero dimension. Depending upon the requirement, whenever in need we can inflate at runtime. This is a classic example to handle when there are complicated views to be handled. When the ViewStub is inflated, it replaces itself in its parent view with the inflated layout resource. Its visibility will exist in the view hierarchy only when setVisibility(int) or inflate() is invoked. The inflated view is added to ViewStub’s parent using the layout parameter. Whenever there are item details, undo messages, or progress indicators, we can think of ViewStub. It reduces memory usage and speeds up rendering by loading the views only when they are needed. One can think that it looks similar to including a tag but it is not. Include tag includes contents in the XML file which is present under the layout folder. So we can have header, footer, left, and right bar XMLs separately but still they are included in the main XML by using include tags. On the other hand, ViewStub is not included but it directly gets loaded when set as setVisibility(int)(for true option) or inflate() is invoked.
Contact Us