分类: Java
2011-11-10 11:01:24
Adapter的作用是ListView界面与数据之间的桥梁,当列表里的每一项显示到页面时,都会调用Adapter的getView方法返回一个View。但是在我们的列表有1000000项或者更多的列表项时,会占用极大的系统资源。
先看看下面的代码(该方式很占资源):
public View getView(int position, View convertView, ViewGroup parent) {
long startTime = System.nanoTime();
View item = mInflater.inflate(R.layout.list_item_icon_text, null);
((TextView) item.findViewById(R.id.text)).setText(DATA[position]);
((ImageView) item.findViewById(R.id.icon)).setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
long endTime = System.nanoTime();
long val = (endTime - startTime) / 1000L;
return item;
}
较好的方式(很多View创建被去除,性能得到了很大的提升):
public View getView(int position, View convertView, ViewGroup parent) {
long startTime = System.nanoTime();
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
}
((TextView) convertView.findViewById(R.id.text)).setText(DATA[position]);
((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
long endTime = System.nanoTime();
long val = (endTime - startTime) / 1000L;
return convertView;
}
更优化的方式:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
return convertView;
}
static class ViewHolder {
TextView text;
ImageView icon;
}
注:代码中的时间差值,只是为了看性能效果。
http://hi.baidu.com/286177943/blog/item/99daff2de6e181f68a139900.html