ViewStub in Android

In this, I just going to show how to use ViewStub in Android. ViewStub we can achieve through <merge> attribute. ViewStub is like a place holder and dynamically we can add layout to our main layout. In viewstub, we have to you the "andorid:layout" attribute and add any layout trough this.

Once again, I am telling this is just a very basic tutorial for ViewStub.

The complete code is,

public class SampleViewStub extends Activity {

ViewStub stub;
boolean click = true;


public void onCreate(Bundle savedInstanceState) {



findViewById(    OnClickListener()  {

public void onClick(View v) {

if (click) {

stub = (ViewStub) findViewById(;


click = false;


<?xml version="1.0" encoding="utf-8"?>

<merge xmlns:android="">

<LinearLayout android:orientation="vertical"

android:layout_width="fill_parent" android:layout_height="fill_parent">

<TextView android:layout_width="fill_parent"

android:layout_height="wrap_content" android:text="Showing ViewStub" />

<Button android:id="@+id/openstub" android:layout_width="fill_parent"

android:layout_height="wrap_content" android:text="Open ViewStub" />

<ViewStub android:id="@+id/stub1" android:inflatedId="@+id/showlayout"

android:layout="@layout/layout1" android:layout_width="fill_parent"

android:layout_height="wrap_content" android:layout_gravity="bottom"/>




<?xml version="1.0" encoding="UTF-8"?>

<LinearLayout xmlns:android=""

android:layout_width="fill_parent" android:layout_height="wrap_content">

<TextView android:id="@+id/label_import" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:text="Textview from Viewstub" />

<Button android:id="@+id/button_cancel" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:minWidth="100dip"

android:text="Next" />


The screenshots are,

You can get the complete source code from here. Github


Popular posts from this blog

Open Gallery and get the selected image in appplication

AlarmManager and Notification in Android

Dismiss or Cancel dialog by swipe gesture