Josh Josh - 4 months ago 22
Android Question

Android - Dynamically Add Views into View

I have a layout for a view -

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0px"
android:orientation="vertical">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/items_header"
style="@style/Home.ListHeader" />

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/items_none"
android:visibility="gone"
style="@style/TextBlock"
android:paddingLeft="6px" />

<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/items_list" />


</LinearLayout>


What I want to do, is in my main activity with a layout like this

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0px"
android:id="@+id/item_wrapper">
</LinearLayout>


I want to loop through my data model and inject multiple views consisting of the first layout into the main layout. I know I can do this by building the controls completely within the code, but I was wondering if there was a way to dynamically build the views so that I can continue using a layout instead of putting everything in code.

Answer

Use the LayoutInflator to create a view based on your layout template, and then inject it into the view where you need it.

LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);

// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");

// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

You may have to adjust the index where you want to insert the view.