ViewStub in Android | AndroidMonks

ViewStub in Android with Example

According to the Android Docs, “A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime”. This means that, it creates a dynamic creation of the View during the runtime of the app rather than Compile time creation (i.e). Consider the case of creating 10 ImageViews and loading 10 different images in a ScrollView. The time taken for the 10 Images to load even though it is in a ScrollView, somewhere outside, it takes up a lot of resource. Instead, if we go for a ViewStub which will load the ImageView only when the User scrolls down, and the View comes in focus of the User, this reduces the load time by a huge amount.

Performance improvement is the main reason to jump to a View Stub, but at the same time, helps in creating a better control over hierarchy of Views at Runtime.

YOU ARE YOUR BOSS
I agree to have my personal information transfered to MailChimp ( more information )
Join over 5.000 visitors who are receiving our free content and learn how to program with Android. The growth of Android is estimated to reach a whooping 83% by 2020. Hop on the train and start making money!
We hate spam. Your email address will not be sold or shared with anyone else.

When a ViewStub is made visible, or when inflate() is invoked, the layout resource is inflated. The View Stub then replaces itself in its parent with the inflated View or Views. Therefore, the ViewStub exists in the view hierarchy until setVisibility(int) or inflate() is invoked. The inflated View is added to the ViewStub’s parent with the ViewStub’s layout parameters. Similarly, you can define/override the inflate View’s id by using the ViewStub’s inflatedId property.

The above paragraph uses the word inflate and deflate, which are key functions of a View Stub. When you inflate a View, you create a View as the Application is running. The need for findViewById is not required here.

ViewStub – Basic Implementation

Implementing a ViewStub is similar to implementing any other View. We will be using the ViewStub tag.

<ViewStub
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout="@layout/activity_main"
    android:inflatedId="@+id/subView"
    android:id="@+id/stubId"/>

We suddenly have additional 3 more properties which we need to explain. What a View stub does is, it inflates a layout that we specify (If you know about Fragments, this is the same process that happens here). Once the layout is inflated, or fits the ViewStub at runtime, the View Stub is now removed from its parent. How will you access the removed View without a id attribute? You will use the inflateId attribute that will hold the View stub reference which inflated our layout (activity_main in this example).

ViewStub – Learning the Public Methods

Let us see what the ViewStub Public methods are. Some of the most commonly used important methods are

getInflatedId()

Returns the inflateId post inflation of the required layout

getLayoutInflater()

Returns the current layout inflater being used.

getLayoutResource()

Returns the layout resource that will be used by setVisibility(int) or inflate() to replace this StubbedView in its parent by another view.

inflate()

Inflate method is used to inflate the layout resource identified by getLayoutResource() and replace this StubbedView in its parent by the inflated layout resource.

setInflatedId(int inflatedId)

Setter to set the value of the inflateId from the activity

setVisibility(int visibility)

When visibility is set to View.VISIBLE or View.INVISIBLEinflate() is invoked and this StubbedView is replaced in its parent by the inflated layout resource.

Creating a ViewStub Example in Android Studio

Let us look at how a ViewStub is created in Android using Android Studio IDE.

Create a simple view_stub.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"
    >
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="View Stub Text"
        android:textSize="40dp"
        android:textColor="@color/colorPrimaryDark"
        android:layout_gravity="center"/>
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toggle View Stub"
        android:id="@+id/toggle_view"
    android:layout_gravity="center"/>

    <ViewStub
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone"
    android:layout="@layout/sample_view_layout"
    android:inflatedId="@+id/subView"
    android:id="@+id/stubId"
    android:layout_gravity="center"/>
</LinearLayout>

Here we are going to inflate the layout of the sample_view_layout file. We will create a sample_view_layout like below.

<?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="wrap_content"
    android:id="@+id/image_view"
    android:src="@drawable/monk"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text_view"
        android:textSize="30dp"
        android:textColor="@color/colorAccent"
        android:text="Inflated Text"/>
</LinearLayout>

Time for our Activity to see how the ViewStub work according to our need. Name it ViewStubActivity.java like below.

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;

public class ViewStubActivity extends Activity {
    ViewStub viewStub;
    Button toggleButton;
    Boolean Visibile = false;
    @Override
    protected  void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_stub);
        viewStub = (ViewStub) findViewById(R.id.stubId);
        toggleButton = findViewById(R.id.toggle_view);
        toggleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(Visibile) {
                    viewStub.setVisibility(View.GONE);
                    Visibile = false;
                }
                else
                {
                    viewStub.setVisibility(View.VISIBLE);
                    Visibile = true;
                }
            }
        });
    }
}

A simple setVisibility() call on the ViewStub shows the View. It can also be inflated using the inflate() public method.

Once done, this is how your final application looks like.

ViewStub Toggle
ViewStub Toggle

 

Drop in any comments you have below.

“Learn and be Curious”

 

 

Also Read  Spinner in Android - Implementation and Overview

Leave a Comment

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