Skip to content
Related Articles

Related Articles

Improve Article

ViewStub in Android with Example

  • Last Updated : 19 Sep, 2021

In Android, ViewStub is a zero-sized invisible View and very flexible that we can lazily inflate layout resources at runtime. It is a dumb and lightweight view and it has zero dimension. Depends upon 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 include 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, 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

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

ViewStub in XML: 

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"
 />

 

 

Java




// viewStubToLearn is the id of ViewStub defined in xml
ViewStub simpleViewStub = ((ViewStub) findViewById(R.id.viewStubToLearn));

 
 

Methods

Description

getInflatedId()To 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 parent with another view. 

The resultant will be an integer value

inflate()

In order to Inflate the layout resource that gets identified by 

getLayoutResource() and replaces 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

idTo uniquely identify a ViewStub
inflatedId

To set the id of the inflated View. Via programmatically 

we can set by using  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. Note that we are going to implement this project using the Kotlin language. 

 



ViewStub in Android sample GIF

Step by Step Implementation

Step 1: Create a New Project

 

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

 

Step 2: Working with the activity_main.xml file

 

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

 

XML




<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#fff"
    >
 
    <!-- 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>

 

 

Step 3: 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 4: 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
    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 5: Working with the MainActivity.kt file

 

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt 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() {
 
    var simpleViewStub: ViewStub? = null
    var showButton: Button? = null
    var hideButton: Button? = null
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // get the reference of ViewStub
        simpleViewStub = findViewById<View>(R.id.viewStubToLearn) as ViewStub
 
        // inflate the layout
        simpleViewStub!!.inflate()
 
        // get the reference of show button
        showButton = findViewById<View>(R.id.showButtonForViewStub) as Button
 
        // get the reference of hide button
        hideButton = findViewById<View>(R.id.hideButtonForViewStub) as Button
 
        // 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
        }
    }
}

 
 

Running the Project on an 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 to activate it by inflating.

 

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :