Android中的ViewHolder

    为什么要使用ViewHodler,因为使用ViewHodler可以节省程序的内粗你开销,具体如下:

@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		final Menu _m = (Menu)list.get(position);
		if(convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.addappslist_item,null);
			holder.flagImage = (MyImageButton)convertView.findViewById(R.id.addapps_flagimage);
			holder.icon = (ImageView)convertView.findViewById(R.id.addapps_icon);
			holder.title = (TextView)convertView.findViewById(R.id.addapps_title);
			//Sets the tag associated with this view. A tag can be used to mark a view in its hierarchy 
			//and does not have to be unique within the hierarchy. Tags can also be used to store data 
			//within a view without resorting to another data structure.
			convertView.setTag(holder); //关联Tag,Tag可以被用来存储与View相关的数据结构
		} else {
			holder = (ViewHolder)convertView.getTag();
		}
		if(_m.getBelong() == 1) {
			holder.flagImage.setBackgroundResource(R.drawable.add_button);
			holder.flagImage.setPosition(position);
			holder.flagImage.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					_m.setBelong(0);
					dButil.updateOneMenu9Item(_m);
					list = dButil.readMenu9Items();
				}
			});
		} else {
			holder.flagImage.setBackgroundResource(R.drawable.noadd_button);
			holder.flagImage.setEnabled(false);
		}
		holder.icon.setBackgroundDrawable(_m.getIcon());
		if(_m.getTitle().contains("概况")) {
			holder.title.setText(INI.REGION_CN + _m.getTitle());
		} else {
			holder.title.setText(_m.getTitle());
		}
		return convertView;
	}
	
	class ViewHolder {
		TextView title;
		ImageView icon;
		MyImageButton flagImage;
	}

    上面是我工程中的一个Adapter中的片段,我们可以使用View.setTag(Object o) 将该View对应的数据结构保存在一个对象中,而不用在getView时每次都调用inflate来创建view的对象。据说inflate是十分占用内存的!!!

你可能感兴趣的:(android,viewholder)