Android api demo裡面有一個編寫高效list adapter的demo,裡面寫瞭建議的兩條高效原則
1. 在getView方法中,重復利用 convertView,convertView是舊的View,建議先判斷是否為空,如果不為空,可以修改其內容來顯示新的row。
public View getView(int position, View convertView, ViewGroup parent) {
SpeechView sv;
if (convertView == null) {
sv = new SpeechView(mContext, mTitles[position],
mDialogue[position]);
} else {
sv = (SpeechView) convertView;
sv.setTitle(mTitles[position]);
sv.setDialogue(mDialogue[position]);
}
return sv;
}
2. 在getView方法中,利用ViewHolder來保存與convertView相關聯的子View,避免調用 findViewById方法,以提高效率
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
return convertView;
}
摘自 達小生