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,

SampleViewStub.java


public class SampleViewStub extends Activity {

ViewStub stub;
boolean click = true;


@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

findViewById(R.id.openstub).setOnClickListener(new    OnClickListener()  {

public void onClick(View v) {

if (click) {

stub = (ViewStub) findViewById(R.id.stub1);

stub.inflate();

click = false;
} 
}
});
}
}



main.xml


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

<merge xmlns:android="http://schemas.android.com/apk/res/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"/>

</LinearLayout>

</merge>



layout1.xml




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



</LinearLayout>


The screenshots are,



You can get the complete source code from here. Github

Comments

Popular posts from this blog

AlarmManager and Notification in Android

Swipe Action and ViewFlipper in Android

Open Gallery and get the selected image in appplication