Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android BaseAdapter: convertView null on getView() re-entry

I am building a ListView with sections according to the technique described at http://bartinger.at/listview-with-sectionsseparators/ . But I would like to extend it by reusing convertView for the non-section items. However, I am finding that the convertView variable is null each time getView() method is entered. Could someone explain why this is the case?

ViewHolder holder;
final ListViewItem item = items.get(position);

if (item.isSection()) {
    Section section = (Section)item;

    convertView = inflater.inflate(R.layout.section, null);
    TextView title = (TextView) convertView.findViewById(R.id.section_title);
    title.setText(section.title);
} else {
    if (convertView == null) {
        Log.d("Adapter", "convertView was null");
    }

    Server server = (Server)item;

    convertView = inflater.inflate(R.layout.server_row, null);
    holder = new ViewHolder();
    holder.serverName = (TextView) convertView.findViewById(R.id.server_name);
    holder.serverStatusIcon = (ImageView)convertView.findViewById(R.id.server_status_icon);
    convertView.setTag(holder);

    holder.serverName.setText(server.name);
}

return convertView;

The list is being created and displayed without errors and contains both sections and non-section items just fine.

like image 264
Marc Avatar asked May 01 '26 22:05

Marc


1 Answers

Are you implementing correctly

getItemViewType (int position) ?

See from Android's documentation:

Returns

An integer representing the type of View. Two views should share the same type if one can be converted to the other in getView(int, View, ViewGroup). Note: Integers must be in the range 0 to getViewTypeCount() - 1. IGNORE_ITEM_VIEW_TYPE can also be returned.

So maybe the convertView is always null because the adapter doesn't know which items belong together, so it doesn't know which ones pass to be recycled...

Try this:

@Override
public int getItemViewType(int position) {
    if (((MyItem)getItem(position)).isHeader()) {
        return 1;
    } else {
        return 0;
    }
}

@Override
public int getViewTypeCount() {
    return 2;
}

The index which you return in getItemViewType is just an identifier to group headers and not-headers together.

In this case you have to implement a method "isHeader" (or analogous) in your model items.

like image 67
User Avatar answered May 04 '26 11:05

User



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!