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