ViewStub in Android with Example
Last Updated :
22 Aug, 2022
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.
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. |
---|
Attributes of ViewStub
Attributes
| Description
|
---|
id | To uniquely identify a ViewStub |
inflated | To set the id of the inflated View. Via programmatically we can set it by using the setInflatedId() method. |
layout |
To supply an identifier for the layout resource to inflate when the ViewStub becomes visible or when forced to do so.
Via programmatically can be set by using the setLayoutResource(int) method.
|
Example
A sample GIF is given below to get an idea about what we are going to do in this article.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Add an Image to the Drawable Folder
Go to the app > res > drawable folder, and we need to provide the images required. For different resolutions, if there is a necessity for bigger or smaller images, it will be under the res folder for different drawable. Here, this image is specified in ImageView in custom_viewstub.xml. So you may download this image and paste it to the drawable folder.

Step 3: Working with the XML Files
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.Â
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:orientation="vertical">
<!-- To show the ViewStub -->
<Button
android:id="@+id/showButtonForViewStub"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="100dp"
android:background="#0f0"
android:text="Show ViewStub"
android:textColor="#fff"
android:textSize="16sp"
android:textStyle="bold|italic" />
<!-- To hide the ViewStub -->
<Button
android:id="@+id/hideButtonForViewStub"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:background="#f00"
android:text="Hide ViewStub"
android:textColor="#fff"
android:textSize="16sp"
android:textStyle="bold|italic" />
<!-- ViewStub, its layout is specified
under layout->custom_viewstub -->
<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" />
</LinearLayout>
Create a New Layout XML FileÂ
Go to the app > res > layout > right-click > New > XML > Layout XML file and name the file as custom_viewstub. Below is the code for the custom_viewstub.xml file.
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:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_gravity="center"
android:src="@drawable/cryptocurrency" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="CRYPTOCURRENCY"
android:textColor="@color/colorAccent" />
</LinearLayout>
Step 4: Working with the MainActivity File
Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Â
Kotlin
import android.app.Activity
import android.os.Bundle
import android.view.View
import android.view.ViewStub
import android.widget.Button
class MainActivity : Activity() {
private lateinit var simpleViewStub: ViewStub
private lateinit var showButton: Button
private lateinit var hideButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get the reference of ViewStub
simpleViewStub = findViewById(R.id.viewStubToLearn)
// inflate the layout
simpleViewStub.inflate()
// get the reference of show button
showButton = findViewById(R.id.showButtonForViewStub)
// get the reference of hide button
hideButton = findViewById(R.id.hideButtonForViewStub)
// perform click event on show button
showButton.setOnClickListener {
// set VISIBLE visibility of ViewStub
simpleViewStub.visibility = View.VISIBLE
}
// perform click event on hide button
hideButton.setOnClickListener {
// set GONE visibility of ViewStub
simpleViewStub.visibility = View.GONE
}
}
}
Java
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
ViewStub simpleViewStub;
Button showButton, hideButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of ViewStub
simpleViewStub = findViewById(R.id.viewStubToLearn);
// inflate the layout
simpleViewStub.inflate();
// get the reference of show button
showButton = findViewById(R.id.showButtonForViewStub);
// get the reference of hide button
hideButton = findViewById(R.id.hideButtonForViewStub);
// perform click event on show button
showButton.setOnClickListener(view -> {
// set VISIBLE visibility of ViewStub
simpleViewStub.setVisibility(View.VISIBLE);
});
// perform click event on hide button
hideButton.setOnClickListener(view -> {
// set GONE visibility of ViewStub
simpleViewStub.setVisibility(View.GONE);
});
}
}
Output: Running on Emulator
On running the project, we can able to see a similar kind of output as attached in the video. So ViewStub is a nice feature in android and whenever in need, we can invoke that which provides enormous memory usage reduction but at the same time can able activate it by inflating.
Similar Reads
TextView in Android with Example
TextView is a simple widget that is seen in every android application. This widget is used to display simple text within the android application. We can add custom styling to the text that we have to show. In this article, we will take a look at How to create a simple Text View in an android applica
2 min read
ViewSwitcher in Android with Example
All android apps will have a feature to switch different views in order to explain/promote their site or product. Visual representation of a product by showing different views will impress the customers easily. In this article, let us see how to bring the "ViewSwitcher" to Android. ViewSwitcher is a
6 min read
TreeView in Android with Example
If you are looking for new UI designs to represent huge data, then there are so many ways to represent this type of data. You can use pie charts, graphs, and many more view types to implement these views. For displaying such huge data then we can prefer using a TreeView. TreeView is similar to that
4 min read
PhotoView in Android with Example
In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displa
2 min read
ViewPager2 in Android with Example
Before going to Viewpager2 let us know about Viewpager. Most of you have used WhatsApp, when you open WhatsApp you can see at the top, there are four sections Camera, Chats, Status, Calls these are the Viewpager. So a Viewpager is an android widget that is used to navigate from one page to another p
6 min read
ViewAnimator in Android with Example
ViewAnimator is a very fascinating and useful feature as it switches between two or more views smoothly and mainly meant for animation features of the views on screens. It is the parent class of ViewFlipper and ViewSwitcher and the main distinction is it can switch between more than 2 views also. It
4 min read
Spinner in Android with Example
Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the c
4 min read
RecyclerView in Android with Example
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be custo
7 min read
Android ListView in Java with Example
A ListView in Android is a type of AdapterView that displays a vertically scrollable list of items, with each item positioned one below the other. Using an adapter, items are inserted into the list from an array or database efficiently. For displaying the items in the list method setAdaptor() is use
3 min read
TextView widget in Android with Examples
Widget refers to the elements of the UI (User Interface) that help the user interact with the Android App. TextView is one of many such widgets which can be used to improve the UI of the app. TextView refers to the widget which displays some text on the screen based on the layout, size, colour, etc
5 min read