Android: How to load layout xml files dynamically during runtime
Posted by blogmeister on
March 19, 2008
Here is a sample code to load XML layout files at runtime within your Android application. Basically, you have to have a Layout tag within your main XML file so that we get to have a placeholder to where we want to store our content.
|
1 2 3 4 5 6 7 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/content1" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff99ccff" /> |
Then in your code, follow this:
|
1 2 3 4 |
LinearLayout ll = (LinearLayout) a.findViewById(R.id.content2); ViewInflate vi = (ViewInflate) a.getSystemService(Context.INFLATE_SERVICE); View vv = vi.inflate(R.layout.mynewxmllayout, null, null); ll.addView(vv, new LinearLayout.LayoutParams(ll.getLayoutParams().width, ll.getLayoutParams().height)); |
where a is the class that extends Activity. If you are going to place this code within your class that extends Activity, you don’t need to include the a. in the code. Of course, this does not restrict to LinearLayout alone. You can use all other layouts to add new Views as its content.
Donations appreciated. Every little $ helps. Or click Google +1.











4 Responses to “Android: How to load layout xml files dynamically during runtime”
This line..
LinearLayout ll = (LinearLayout) a.findViewById(R.id.content2);
Should be..
LinearLayout ll = (LinearLayout) a.findViewById(R.id.content1);
Otherwise it wont work.
By Paul Teale on Dec 31, 2010
This is not dynamically loading a layout xml file. This is dynamically creating a layout + views in code.
By Craig on Jan 10, 2011
what are “a” ? is it a class?
By yogibali on Oct 26, 2011
@yogibali: it’s in my post “where a is the class that extends Activity”. you can remove ‘a’ if the code is within your activity class
By tech on Oct 26, 2011