Android: Use setTag and getTag of View
1. Used to differentiate many similar views
For example:
button1.setOnClickListener(new OnClickListener ... );button2.setOnClickListener(new OnClickListener ... );
They may execute similar logic, but you must set two independent OnClick events for the two buttons respectively,
public void onClick(View v) { doAction(1); // 1 for button1, 2 for button2, etc.}
This is because onClick has only one View parameter. We can do this using setTag and getTag:
button1.setTag(1);button2.setTag(2);
We can set the two buttons to the same OnClickListener, for example:
listener = new OnClickListener() { @Override public void onClick(View v) { doAction(v.getTag()); }};
In this way, it can be distinguished by getTag.
2. Used for reuse of ListView
When writing a custom adapter, we usually use it, for example:
static class ViewHolder { TextView tvPost; TextView tvDate; ImageView thumb;}public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = myContext.getLayoutInflater(); convertView = inflater.inflate(R.layout.postitem, null); ViewHolder vh = new ViewHolder(); vh.tvPost = (TextView)convertView.findViewById(R.id.postTitleLabel); vh.tvDate = (TextView)convertView.findViewById(R.id.postDateLabel); vh.thumb = (ImageView)convertView.findViewById(R.id.postThumb); convertView.setTag(vh); } ....................}
3. Note:
In addition to the above situations, we try not to use them directly. The reason is:
1. code readability: it will cause troubles to other programmers.
2. Because setTag and getTag are set to an Object, a class conversion exception may occur.
However, there is a better method after android4.0: setTag (int key, Object tag) can be similar Key-Value Pair Access.