《第一行代码》 随手笔记——第三章 UI开发的点点滴滴

 3.5.3提升ListView的运行效率

  1、

View view;
		if (convertView == null) {
			view = LayoutInflater.from(getContext()).inflate(resourceId, null);
		} else {
			view = convertView;
		}

2、每次在getView()方法中还是会调用View的findViewById()方法来获取一次控件的实例。我们可以借助一个ViewHolder来对这部分性能进行优化

public class FruitAdapter extends ArrayAdapter {
	……
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Fruit fruit = getItem(position);
		View view;
		ViewHolder viewHolder;
		if (convertView == null) {
			view = LayoutInflater.from(getContext()).inflate(resourceId, null);
			viewHolder = new ViewHolder();
			viewHolder.fruitImage = (ImageView) view.findViewById (R.id.fruit_image);
			viewHolder.fruitName = (TextView) view.findViewById (R.id.fruit_name);
			view.setTag(viewHolder); // 将ViewHolder存储在View中
		} else {
			view = convertView;
			viewHolder = (ViewHolder) view.getTag(); // 重新获取ViewHolder
		}
		viewHolder.fruitImage.setImageResource(fruit.getImageId());
		viewHolder.fruitName.setText(fruit.getName());
		return view;
	}
	
	class ViewHolder {
		
		ImageView fruitImage;
		
		TextView fruitName;
		
	}
}



你可能感兴趣的:(《第一行代码》 随手笔记——第三章 UI开发的点点滴滴)