Android using layouts as a template for creating multiple layout instances
You can easily do this, you just have to break it down. First you load the layout that you want to insert your dynamic views into. Then you inflate your subview and populate it as many times as you need. Then you add the view to your parent layout, and finally set the content view of the activity to the parent view.
Here's an example:
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);
for (int i = 0; i < 3; i++) {
View custom = inflater.inflate(R.layout.custom, null);
TextView tv = (TextView) custom.findViewById(R.id.text);
tv.setText("Custom View " + i);
parent.addView(custom);
}
setContentView(parent);
here is the main.xml file that I am inserting into:
<?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="fill_parent"
android:orientation="vertical" >
</LinearLayout>
and here is the custom.xml view that I inflate, populate and dynamically insert:
<?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"
android:orientation="horizontal" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
To annyone still looking for a similar solution, apparently you can also use include
directly in xml and still be able to refer to them in code:
LinearLayout row1 = (LinearLayout) findViewById(R.id.row1)
TextView text1 = row1.findViewById(R.id.text);
LinearLayout row2 = (LinearLayout) findViewById(R.id.row2)
TextView text2 = row2.findViewById(R.id.text);
Source: Romain Guy