上例使用臨時數據來綁定列表項解決那些載入費時的列表項在列表滾動時的性能問題,本例介紹如果編寫一個高效的List Adapter ,其實也不是什麼特別的技術,主要是:
重用getView 傳入參數convertView ,避免多次從XML中展開View。
設計瞭一個ViewHolder,用來存放一個TextView 和ImageView,避免每次都調用findViewById。
說到底就是使用變量把一些本來需要多次調用inflate或是findViewById的對象暫存起來,下次再調用getView時,可以重用這些對象,從而提高getView 的效率。
[java]
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();
}
// Bind the data efficiently with the holder.
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1
? mIcon1 : mIcon2);
return convertView;
}
static class ViewHolder {
TextView text;
ImageView icon;
}
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();
}
// Bind the data efficiently with the holder.
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1
? mIcon1 : mIcon2);
return convertView;
}
static class ViewHolder {
TextView text;
ImageView icon;
}
這裡至少說明瞭List Adapter的getView 傳入的convertView 本身是重用的,而不是每次創建瞭一個新的convertView。