What is the purpose of `convertView` in ListView adapter?

前端 未结 4 1977
逝去的感伤
逝去的感伤 2020-12-08 07:58

In android, I usually use MyAdapter extends ArrayAdapter to create view for the ListView, and as a result, I have to override the function

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 08:29

    Shorter Version :

    Please read @Alex Lockwood's and @jeet's answer.

    My Answer :

    Before why, which is the better/proper way of using convertView in getView()? Well explained by Romain Guy in this video.

    An example,

    @Override
     public View getView(final int position, View convertView, ViewGroup parent)            {
       View rowView = convertView;
       ViewHolder holderObject;
    
     if (rowView == null) {
         rowView = inflater.inflate(R.layout.list_single_post_or_comment, parent, false);
         holderObject = new HolderForContent();
         mapHolder(holderObject, rowView);
         rowView.setTag(holderObject);
       } else {
         holderObject = (HolderForContent) convertView.getTag();
       }
       setHolderValues(holderObject, position);
       return rowView;
     }
     
     private class ViewHolder {
        TextView mTextView;
     }
     
     mapHolder(holderObject, rowView) {
        //assume R.id.mTextView exists
        holderObject.mTextView = rowView.findViewById(R.id.mTextView);
     }
     
     setHolderValues(holderObject, position) {
        //assume this arrayList exists
        String mString = arrayList.get(position).mTextViewContent;
        holderObject.mTextView.setText(mString);
     }
    

    Above is just an example, you can follow any type of pattern. But remember this,

    @Override
     public View getView(final int position, View convertView, ViewGroup parent) {
     
       if (convertView == null) {
            // todo : inflate rowView. Map view in xml.
       } else {
            // todo : get already defined view references
       }
    
       // todo : set data to display
     
     return rowView;
     
     }
    

    Now coming to purpose of convertView. The why?

    convertView is used for performance optimization [see chart in slide 14 by Romain Guy] by not recreating view that was created already.

    Sources : Any corrections are welcome. I actually gathered this info through these links,

    Read about getView() in Android developer documentation.

    Romain Guy speaking about getView() in video "Turbo Charge Your UI" at Google IO 2009 and material used for presentation.

    A wonderful blog by Lucas Rocha.

    Those who want to take a deep dive into source code : ListView and a sample implementation of getView() can be seen in source code for arrayAdapter.

    Similar SO posts.

    what-is-convertview-parameter-in-arrayadapter-getview-method

    how-do-i-choose-convertview-to-reuse

    how-does-the-getview-method-work-when-creating-your-own-custom-adapter

提交回复
热议问题