asmodeoux asmodeoux - 1 month ago 12
Android Question

How can I setText to TextViews created in cycle?

I created a cycle to make a Layout with a TextView for every unit in an Array:

for(int x = 0; x<coffeeSets.length; x++) {


final View view = getLayoutInflater().inflate(R.layout.custom_list, container);
TextView tv = (TextView) view.findViewById(R.id.tv1);
TextView tv2 = (TextView) view.findViewById(R.id.tv2);
tv.setText(coffeeSets[x].name);
tv2.setText(coffeeSets[x].price + "\u20BD");
}


Here is the xml of the custom layout, if that matters:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="@color/white"
android:layout_height="wrap_content">


<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
/>

<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:layout_marginRight="20dp"
/>


</RelativeLayout>


The problem is that it creates as many Layouts as I need, but it can only set the text for the first one:

The first layout gets the text of the last, and the last one gets empty

I understand that it because tv and tv2 are set to be 1st layout's textview, but how can I set text to other ones?

Answer Source

You can make inflate(R.layout.custom_list, container, false) and add the layout(container.addView(view);) manually, to appear on the screen. check below code.

The reason is if you set it to true or if you give only that layout it will be attached to the parent layout immediately, you cant add multiple items again because that view will already be added. For more detail about Inflator, you can read this article

final LinearLayout container = (LinearLayout) findViewById(R.id.container);

for(int x = 0; x<coffeeSets.length; x++) {


    final View view = getLayoutInflater().inflate(R.layout.custom_list, container, false); // we can set attachToRoot as false  
    TextView tv = (TextView) view.findViewById(R.id.tv1);
    TextView tv2 = (TextView) view.findViewById(R.id.tv2);
    tv.setText(coffeeSets[x].name);
    tv2.setText(coffeeSets[x].price + "\u20BD");

    container.addView(view); // this you missed 
}