How to load XML layout file dynamically?
Here is a sample code to load two XML layout file in one java activity class.
layout_1.xml is main XML file, which has a placeholder at the bottom. This placeholder is used to show the content of second xml file.
layout_1.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >
<TextView android:id=”@+id/box_0″
android:layout_width=”fill_parent”
android:layout_height=”40px”
android:background=”@drawable/blue”
android:text=”This is main layout” />
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/box_1″
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_below=”@+id/box_0″ >
</LinearLayout>
</RelativeLayout>
In above code box_1 is the placeholder. Now take a look at second layout.
layout_2.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/box”
android:orientation=”horizontal”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >
<TextView android:id=”@+id/box_0″
android:layout_width=”fill_parent”
android:layout_height=”40px”
android:background=”@drawable/yellow”
android:text=”This is second layout” />
</LinearLayout>
And below is the java code to load both layouts.
Java code
setContentView(R.layout.itest);
LinearLayout ll = (LinearLayout) findViewById(R.id.box_1);
View vv = View.inflate(PrivacySettings.this, R.layout.itest2, null);
ll.addView(vv, new LinearLayout.LayoutParams( ll.getLayoutParams().width,
ll.getLayoutParams().height));
Screen Shot
This kind of runtime XML loading can be used for any layout.