Explain individual role of convertView and View Holder Pattern in ListView

322 Views Asked by At

Can anyone explain the individual role of convertView and View Holder Pattern in ListView, and how they increased the efficiency of listview?

private class PersonsAdapter extends ArrayAdapter<Person> {

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

        ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_entry, null);
            holder = new ViewHolder();
            holder.nameTextView = (TextView) convertView.findViewById(R.id.person_name);
            holder.surnameTextView = (TextView) convertView.findViewById(R.id.person_surname);
            holder.personImageView = (ImageView) convertView.findViewById(R.id.person_image);
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        Person person = getItem(position);

        holder.nameTextView.setText(person.getName());
        holder.surnameTextView.setText(person.getSurname());
        //holder.personImageView.setImageBitmap(person.getImage());

        return convertView;
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER
  • convertView

it's a view that was previously inflated (when convertView==null) and was on the screen, but now have been scrolled out of the screen, so you can re-use it to display data from the view that will enter the screen soon.

improves performance by reducing view inflation (calls to inflater.inflate are expensive), reduces garbage collection, and reduces memory allocation.

  • view holder

keeps a direct reference to your view.

potentially improves performance because findViewById is a for-loop going around the view hierarchy that can potentially eat away quite precious time of the UI thread. This improvement might be small, but in a fast scrolling list, every nano-second counts to have a nice smoth 60fps.

0
On

There are many posts about this in SO. But in short it is about reusing objects in the ListView instead of instantiating new ones. In a ListView there is a fixed number of items on screen. So when scorlling while a new item might come in from the bottom a previous item will be disapearing from the top.

So the convertview would be the object storing the data that is disappearing, which you can reuse to store the new incoming data.

If converView is null, you need to create a new view to store the incoming data. If it is not null you can reuse it for new data instead of creating a new view.