Chan Chan - 1 year ago 54
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

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

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(;
holder.textViewText2 = (TextView) convertView.findViewById(;
holder.table = (TableLayout) convertView.findViewById(;
else {
holder = (ItemViewHolder) convertView.getTag();


// 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");
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
in which I can add another widget at runtime for each item? Any suggestion would be greatly appreciated.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download