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);
}
}
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;
}