短版:
请阅读@Alex Lockwood 和@jeet 的回答。
我的答案:
在为什么之前,在getView() 中使用convertView 的更好/正确 方式是什么? Romain Guy 在video 中很好地解释了。
示例,
@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);
}
以上只是一个示例,您可以遵循任何类型的模式。但是记住这一点,
@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;
}
现在来到convertView 的目的。 为什么?
convertView 用于性能优化 [see 在幻灯片 14 中由 Romain Guy 绘制的图表],而不是重新创建已经创建的视图。
来源:
欢迎任何更正。我实际上是通过这些链接收集这些信息的,
在 Android 开发人员 documentation 中了解 getView()。
Romain Guy 在 Google IO 2009 的 video“Turbo Charge Your UI”中谈到 getView(),material 用于演示。
Lucas Rocha 的精彩 blog。
想要深入了解源代码的人:ListView 和 getView() 的示例 implementation 可以在 arrayAdapter 的源代码中看到。
类似的 SO 帖子。
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