View 中 setTag & getTag

setTag(finalObject tag)        //把一个标签与一个控件关联,一个标签可以在层次图中用来标记一个控件,
                               //在层次图中并不唯一。标签也可以在控件中存储数据,不需要存储成另外的数据格式。
 
getTag()                       //得到相应的tag
使用:
1.在ListView自定义的Adapter中使用的比较多。
public View getView(int arg0, View arg1, ViewGroup arg2) {
		// TODO Auto-generated method stub
		Viewholder viewholder;
		if (arg1 == null) {
			View view = LayoutInflater.from(context).inflate(
					R.layout.devicelist_item, null);
			viewholder = new Viewholder(); 
			viewholder.name = (TextView) view.findViewById(R.id.device_name);
			viewholder.space = (TextView) view.findViewById(R.id.device_space);
			viewholder.system = (TextView) view
					.findViewById(R.id.device_system);
			viewholder.imageView=(ImageView) view.findViewById(R.id.device_image);
			view.setTag(viewholder);
			arg1 = view;
		} else {
			viewholder = (Viewholder) arg1.getTag();
		}
		String string = devices.get(arg0).getName();
		viewholder.name.setText(string.substring(string.lastIndexOf("/") + 1,
				string.length()));
		viewholder.space.setText(devices.get(arg0).getSpace());
		viewholder.system.setText(devices.get(arg0).getSystem());
		return arg1;
	}
	class Viewholder {
		TextView name;
		TextView space;
		TextView system;
		ImageView imageView;
	}
2.标记View
private Button callBtn = null;
callBtn = (Button) findViewById(R.id.callBtn);
callBtn.setTag(6);
callBtn.setOnClickListener(this);
public void onClick(View v) {
	// TODO Auto-generated method stub
	if((Integer)v.getTag()==6){
		ComponentName comp = new ComponentName("com.zmq.firstapp", "com.zmq.firstapp.TestActivity");
		Intent intent = new Intent();
		intent.setComponent(comp);
		startActivity(intent);
	}
}
在Android中的源码:
protected Object mTag;
 /**
     * Returns this view's tag.
     *
     * @return the Object stored in this view as a tag
     *
     * @see #setTag(Object)
     * @see #getTag(int)
     */
    @ViewDebug.ExportedProperty
    public Object getTag() {
        return mTag;
    }
    /**
     * 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.
     *
     * @param tag an Object to tag the view with
     *
     * @see #getTag()
     * @see #setTag(int, Object)
     */
    public void setTag(final Object tag) {
        mTag = tag;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值