Android BaseAdapter使用及listview优化

public class PurchaseAdapter extends BaseAdapter{

	private LayoutInflater inflater=null;
	private List> mlist=null;
	private HashMap mMap=null;
	
	public PurchaseAdapter(Context context,List> list) {
		inflater=(LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.mlist=list;
	}
	
	@Override
	public int getCount() {
		return mlist.size();
	}

	@Override
	public Object getItem(int position) {
		return mlist.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder=null;
		if(convertView==null){
			convertView=inflater.inflate(R.layout.activity_shipping_address_list_item, null);
			holder=new ViewHolder();
			holder.tv_username=(TextView) convertView.findViewById(R.id.activity_shipping_address_list_username);
			holder.tv_address_district=(TextView) convertView.findViewById(R.id.activity_shipping_address_list_address_district);
			holder.tv_address_details=(TextView) convertView.findViewById(R.id.activity_shipping_address_list_address_detail);
			convertView.setTag(holder);
		}else{
			holder=(ViewHolder) convertView.getTag();
		}
		mMap=(HashMap) mlist.get(position);
		holder.tv_username.setText(mMap.get("user_name").toString());
		holder.tv_address_district.setText(mMap.get("address_district").toString());
		holder.tv_address_details.setText(mMap.get("address_details").toString());
		
		return convertView;
	}
	
	static class ViewHolder{
		TextView tv_username; //收货人真实姓名
		TextView tv_address_district; //收获地址(太原市杏花岭区)
		TextView tv_address_details; //收获详细地址(北大街88号2号楼502)
	}

}

使用静态的ViewHoulder的目的则是节省了findViewById的时间。如果不使用ViewHolder,每次getView的时候都需要得到一次子布局,而这也是很耗时并且耗资源的;如果使用了ViewHolder作为子布局的缓存,使用View的setTag方法将缓存与每个item绑定,则也可以省去了findViewById的事件;而将ViewHolder设置为static的目的是指在初始化Adapter时初始化一次这个内部类,否则将会在每次创建Adapter时都要初始化一次,而这是没有必要的。

你可能感兴趣的:(Android)