public View getView(int position, View convertView, ViewGroup parent) { 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); return item; }怎么样?如果超过1000000项时,后果不堪设想!您可千万别这么写! 我们再来看看下面的代码:
public View getView(int position, View convertView, ViewGroup parent) { 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); return convertView; }怎么样,上面的代码是不是好了很多?系统将会减少创建很多View。性能得到了很大的提升。 还有没有优化的方法呢? 答案是肯定的:
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; }怎么样?会不会又给您的系统带来很大的提升呢?看看下面三种方式的性能对比图您就知道了! 本文是Google I/O 2009 Romain Guy 所讲的内容,这里只做简单介绍,相信一看代码就能看懂!有问题请留言! 来源:www.ideasandroid.com 原文: http://www.ideasandroid.com/archives/295