简体   繁体   中英

Understanding convertView parameter of GetView method

Hello android developers, I have read documentation on getView method of BaseAdapter and what I understood is view can be reused/recycled,so should check that this view is non-null and of an appropriate type before using. In my case every time convertview is null and new view is created. Though list is populated correctly,but I would like to know when view will be recycled and when it will create new view.

Basically it is recycled when you scroll your list. When item is hidden - it can be recycled and used as new visible item. Try to add ~100 items and scroll them and check how many views really created.

so should check that this view is non-null and of an appropriate type before using

So, i believe you are using multiple Layouts in the ListView.

In my case every time convertview is null and new view is created

This might be because, you didn't use:

@Override
public int getItemViewType(int position) {

    return dataArray[position].getType();
}
@Override
public int getViewTypeCount() {

    return TYPE_MAX_COUNT;
}

Though list is populated correctly,but I would like to know when view will be recycled and when it will create new view

It won't recycle automatically, you should check for the availability of ConvertView(not null) and use it, instead of inflating a new View.

This way:

public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;
    int type = getItemViewType(position);
    if (convertView == null) {

        holder = new ViewHolder();
        switch (type) {
        case TYPE1:
        //inflate type1
        break;
        case TYPE2:
        //inflate type2
        break;
        }
    convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
}

And ConvertView is available (not null) to be resused, when the View of that particular type is inflated at least once and is no longer visible, because you scrolled the List.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM