Khant Thu Linn
Khant Thu Linn

Reputation: 6143

Inflate programmatically for android layout

I want to reuse existing layout again and again instead of creating/writing new xml. Currently, I have like this.

enter image description here

I want to have like this programmatically instead of writing in xml (may be I want to write it in Activity).

enter image description here

May I know how to do? Also, another problem is that if I reuse like that, "id" will be same. If so, how can I set text?

enter image description here

Upvotes: 2

Views: 4051

Answers (1)

samgak
samgak

Reputation: 24427

Add a LinearLayout to your layout, and then inflate the header_description layout in code multiple times and add it to the LinearLayout.

Change the layout to be similar to this:

<include layout="@layout/header_list_image"/>

<LinearLayout
    android:layout_id="@+id/description_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_contents"
    android:orientation="vertical" >

<include layout="@layout/header_url"/>
<include layout="@layout/row_listing_like_comment_share"/>
<include layout="@layout/header_comment_separator"/>

In code, find the LinearLayout using the id, and the inflate the description layouts one at a time and add them in your onCreate() function:

LinearLayout layout = (LinearLayout)findViewById(R.id.description_layout);
LayoutInflater inflater = getLayoutInflater();

// add description layouts:
for(int i = 0; i < count; i++)
{
     // inflate the header description layout and add it to the linear layout:
     View descriptionLayout = inflater.inflate(R.layout.header_description, null, false);
     layout.addView(descriptionLayout);

     // you can set text here too:
     TextView textView = descriptionLayout.findViewById(R.id.text_view);
     textView.setText("some text");
}

Also, another problem is that if I reuse like that, "id" will be same. If so, how can I set text?

call findViewById() on the inflated layout e.g:

descriptionLayout.findViewById(R.id.text_view);

not like this:

findViewById(R.id.text_view);

Upvotes: 3

Related Questions