Learn Android UI

ViewStub Tutorial With Example In Android Studio

In Android, ViewStub is zero sized invisible View that can be used to lazily inflate layout resource at runtime. It is a dumb and lightweight view. The special thing about ViewStub is that it neither participate nor draw anything in the layout. It has zero dimension.

By term inflate we mean load the layout resource at runtime and then ViewStub replace itself in its parent by the inflated layout resource.

Layout referenced by a ViewStub is inflated and added to the UI only when we decide. It means Whenever a ViewStub is made visible, or when inflate() method invoked, the layout resource is inflated and then ViewStub replaces itself in its parent with the inflated Resource. The ViewStub only exists in the view hierarchy until setVisibility(int) or inflate() is invoked. The inflated View is added to the ViewStub’s parent using layout parameter.

Important Note: Sometimes our layout might require complex views that are rarely used. Whether they are item details, undo messages, or progress indicators. You can reduce memory usage and speed up rendering by loading the views only when they are needed.


Basic ViewStub XML Code:

<ViewStub android:id="@+id/simpleViewStub"
android:inflatedId="@+id/subView"
android:layout="@layout/mySubView"
android:layout_width="fill_parent"
android:layout_height="200dp" />

The ViewStub thus defined can be found using the id “simpleViewStub”. After inflation of the layout resource “mySubView,” the ViewStub is removed from its parent. The View created by inflating the layout resource “mySubView” can be found using the id “subView,” specified by the inflatedId property. The inflated View is finally assigned a width of 200dip and a height of 200dip.


Difference between ViewStub and include tag:

The include tag will just include the xml content’s in your xml file. It’s a nice way to share layout parts between different layout’s. The ViewStub tag is a little bit different because it is not directly included, and will be loaded only when you actually need it, i.e when you set ViewStub’s visibility to “true”.

This is a nice optimization because you could have a complex layout with tons of small views, complex views or headers anywhere, and still have your Activity load up really fast. Once you use one of those views, it’ll be loaded.


Important Methods Of ViewStub:

Let’s we discuss some important methods of ViewStub that may be called in order to manage the ViewStub.

1. getInflatedId(): This method is used to get the id taken by the inflated view. This method returns an integer type value.

Below we then get the same id using getInfaltedId() method.

ViewStub simpleViewStub = new ViewStub(getApplicationContext()); // get the reference of ViewStub
int infaltedId = simpleViewStub.getInflatedId(); // get the infalted layout's id

2. setLayoutResource(int layoutResource): This method is used to set the layout resource to inflate when this StubbedView becomes visible or invisible or when inflate() is invoked.

Below we set the layout resource that is used while inflating.

ViewStub simpleViewStub = new ViewStub(getApplicationContext()); // get the reference of ViewStub
simpleViewStub.setLayoutResource(R.layout.stub_layout); // set layout resource to inflate

3. getLayoutResource(): This method is used to get the layout resource that will be used bysetVisibility(int) or inflate() to replace this StubbedView in its parent by another view. This method returns an integer type value.

Below we firstly set the layout resource and then get the layout resource that will be used by setVisibility(int) or inflate() to replace this StubbedView in its parent by another view.

ViewStub simpleViewStub = new ViewStub(getApplicationContext()); // get the reference of ViewStub
simpleViewStub.getLayoutResource(R.layout.stub_layout); // set layout resource to inflate
int layoutReosource = simpleViewStub.getLayoutResource(); // get layout resource that inflates

4. inflate(): This method is used to Inflates the layout resource identified by getLayoutResource() and replaces this StubbedView in its parent by the inflated layout resource.

Below we inflate the layout resource that replaces this StubbedView in its parent by the  inflated layout resource.

ViewStub simpleViewStub = (ViewStub) findViewById(R.id.simpleViewStub); // get the reference of ViewStub
View inflated = simpleViewStub.inflate(); // inflate the layout resource

5. setVisibility(int visibility): This method is used to visibility of the StubView. When visibility is set toVISIBLE or INVISIBLE, inflate() is invoked and this StubbedView is replaced in its parent by the inflated layout resource.

Below we set the INVISIBLE visibility of ViewStub.

ViewStub simpleViewStub = new ViewStub(getApplicationContext()); // get the reference of ViewStub
simpleViewStub.setVisibility(View.INVISIBLE); // set invisible visibility of ViewStub

6. setOnInflateListener(OnInflateListenerinflateListener): This method is used to listener event when we inflate the ViewStub. It specifies the inflate listener to be notified after this ViewStub successfully inflated its layout resource.

Below we show the use of setOnInflateListener event.

ViewStub simpleViewStub = new ViewStub(getApplicationContext()); // get the reference of ViewStub
// perform setOnInflateListener event
simpleViewStub.setOnInflateListener(new ViewStub.OnInflateListener() {
@Override
public void onInflate(ViewStub stub, View inflated) {
// do something here.
}
});

Attributes of ViewStub:

Now let’s we discuss some common attributes of a ViewStub that helps us to configure it in our layout (xml).

1. id: This attribute is used to uniquely identify a ViewStub.

Below we set the “simpleViewStub” id of the ViewStub that is used to uniquely identify it.

<ViewStub android:id="@+id/simpleViewStub"
android:layout_width="fill_parent"
android:layout_height="200dip" />

2. inflatedId: This attribute is used to set the id of the inflated View. We can also set the id of inflated view programmatically means in java class by using setInflatedId() method.

Below we set the “mySubView’ id of the inflated view.

<ViewStub android:id="@+id/simpleViewStub"
android:inflatedId="@+id/subView"
android:layout_width="fill_parent"
android:layout_height="200dip" />

3. layout: This attribute is used to supply an identifier for the layout resource to inflate when the ViewStub becomes visible or when forced to do so. We can also set layout resource programmatically means in java class by using setLayoutResource(int) method.

Below we set the layout resource that is used while inflating.

<ViewStub android:id="@+id/simpleViewStub"
android:inflatedId="@+id/subView"
android:layout="@layout/mySubView"
android:layout_width="fill_parent"
android:layout_height="200dp" />

ViewStub Example In Android Studio:

Below is the example of ViewStub in which we display a ViewStub and two buttons. Firstly we get the reference of Button’s and ViewStub and then inflate the layout resource. In this we perform click events on Show and Hide Button’s. Show Button is used to show the inflated view and hide button is used to hide the inflated view from the screen. In inflated view i.e custom_stub.xml we display a ImageView with a TextView.

Below you can download code, see final output and step by step explanation of example:

Download Code ?

ViewStub Example In Android Studio

Step 1: Create a new project and name it ViewStubExample

Step 2: Open res -> layout ->activity_main.xml (or) main.xml and add following code:

In this step we open xml file and then add two Button’s and a ViewStub. We also add custom_stub layout in the ViewStub.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<Button
android:id="@+id/showButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:background="#0f0"
android:text="Show"
android:textColor="#fff"
android:textSize="18sp"
android:textStyle="bold" />

<Button
android:id="@+id/hideButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:background="#f00"
android:text="Hide"
android:textColor="#fff"
android:textSize="18sp"
android:textStyle="bold" />

<ViewStub
android:id="@+id/simpleViewStub"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:inflatedId="@+id/inflatedview"
android:layout="@layout/custom_stub" />
</LinearLayout>

Step 3: Create a new xml file i.e custom_stub.xml inside layout and add the below code:

In this file we create a ImageView with a TextView i.e used while inflating the layout. Make sure to add a image name image1 in drawable folder.

<?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:orientation="vertical">

<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_gravity="center"
android:src="@drawable/image1" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="CM PUNK"
android:textColor="#000" />

</LinearLayout>

Step 4: Open   src -> package -> MainActivity.java

In this step Firstly we get the reference of Button’s and ViewStub and then inflate the layout resource. In this we perform click events on Show and Hide Button’s. Show Button is used to show the inflated view and hide button is used to hide the inflated view from the screen. In inflated view i.e custom_stub.xml we display a ImageView with a TextView.

package example.abhiandroid.galleryexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;

public class MainActivity extends Activity {
ViewStub simpleViewStub;
Button showButton, hideButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleViewStub = ((ViewStub) findViewById(R.id.simpleViewStub)); // get the reference of ViewStub
simpleViewStub.inflate(); // inflate the layout
showButton = (Button) findViewById(R.id.showButton); // get the reference of show button
hideButton = (Button) findViewById(R.id.hideButton); // get the reference of hide buttton
// perform click event on show button
showButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// set VISIBLE visibility of ViewStub
simpleViewStub.setVisibility(View.VISIBLE);
}
});
// perform click event on hide button
hideButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// set GONE visibility of ViewStub
simpleViewStub.setVisibility(View.GONE);
}
});
}
}

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!

2 thoughts on “ViewStub Tutorial With Example In Android Studio”

Leave a Reply

Your email address will not be published. Required fields are marked *



Also Read:

Download Free - Master Android App Development Sidebar

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!
close-link

Android Developer Facebook Group Free

Premium Project Source Code:




DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!
close-link

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!
close-link

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!
close-link

See How AbhiAndroid Step By Step Video Training Helps You Master Android App Development

Video Training - Unlock step by step video training with new content added regularly. Develop Android Apps.
Android App Source Code - Get amazing Ecommerce, Food Ordering and Ultimate WebView source code with documentation.
GET ACCESS NOW
close-link

With a very poor revenue from selling source code files or using Google AdSense, we need your help to survive this website. Please contribute any amount you can afford
Pay
* Terms & Conditions Apply
close-link