Anand Sunderraman
Anand Sunderraman

Reputation: 8138

Android - Reuse inflated View

Following is a layout that I want to reuse

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:id="@+id/widget_layout"
    android:layout_weight="1"
    android:padding="5dip"
    android:layout_margin="2dip"
    android:background="@drawable/round_corners"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/widget_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="New Source"
        android:textStyle="bold" />

</LinearLayout>

I use it in my activity onCreate method as follows

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.widget_container_layout);
    LayoutInflater inflater =  getLayoutInflater();
    HorizontalScrollView news_scroll = (HorizontalScrollView)findViewById(R.id.news_scroll);
    LinearLayout newsContainer = (LinearLayout) inflater.inflate(R.layout.scroll_layout, null);
    TextView widgetTitle;
    LinearLayout widget_layout;

    for(int i = 0; i < 6; i++) {
        widget_layout = (LinearLayout) inflater.inflate(R.layout.widget_layout, 
        newsContainer).findViewById(R.id.widget_layout);
        widgetTitle = (TextView)(widget_layout.getChildAt(0));
        widgetTitle.setText("New Source " + i);
    }

    news_scroll.addView(newsContainer);
}

So I get my Linear Layout called widget_layout added 6 times to my newsContainer Linear Layout. But the text does not reflect properly.

I expect to see 6 text boxes with text as

New Source 0 New Source 1 New Source 2 New Source 3 New Source 4 New Source 5

But the output I get is

New Source 5 New Source 0 New Source 0 New Source 0 New Source 0 New Source 0

Upvotes: 0

Views: 2602

Answers (1)

stan0
stan0

Reputation: 11807

All inflated widget_layouts in the news_container have the same ID. It looks like findViewById in the loop is not returning the last added widget but just some widget with that ID. Try, instead, inflating the widget with null parent and then add it to the container. Something like this:

for() {
    widget_layout = (LinearLayout) inflater.inflate(R.layout.widget_layout, null);
    widgetTitle...
    news_container.addView(widget_layout);
}

Check LinearLayout's addView for more info and options.

Upvotes: 1

Related Questions