Chan Chan - 18 days ago 5
Android Question

Is it possible to add different views for a ListView at runtime?

I ran into a situation where I need to make each item of a

ListView
have different views. For example,
the first item might have a
TextView
and an
ImageView
, where the second item might have a
Button
and a
TextView
.

My initial attempt was using a table layout nested inside an item adapter, but it doesn't work.

public View getView(int position, View convertView, ViewGroup parent) {
ItemViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.user_activity_item, null);
holder = new ItemViewHolder();
holder.textViewText = (TextView) convertView.findViewById(R.id.user_activity_item_xml_textview_user_name);
holder.textViewText2 = (TextView) convertView.findViewById(R.id.user_activity_item_xml_textview_user_where);
holder.table = (TableLayout) convertView.findViewById(R.id.user_activity_item_xml_tablelayout_activity_table);
convertView.setTag(holder);
}
else {
holder = (ItemViewHolder) convertView.getTag();
}

holder.textViewText.setText(items.get(position));
holder.textViewText2.setText(items.get(position));

// add a new row
TableRow row = new TableRow(context);
row.setLayoutParams(new android.widget.TableRow.LayoutParams(android.widget.TableRow.LayoutParams.FILL_PARENT, android.widget.TableRow.LayoutParams.WRAP_CONTENT));
ImageView i = new ImageView(context);
TextView t = new TextView(context);
t.setText("Some texts");
row.addView(i);
row.addView(t);
holder.table.addView(row, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
return convertView;
}


Each time the list got loaded, the table got modified accordingly. So the number of items keeps increasing. So my question is, is there a way to handle this situation? What can I do to make a dynamic
ListView
in which I can add another widget at runtime for each item? Any suggestion would be greatly appreciated.

Answer

Set convertView = null at the start of method. it will work.

Comments