Android: Use setTag and getTag of View, settaggettag
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 will be a better method after android4.0: setTag (int key, Object tag) can be accessed in a way similar to <k, v> key-value pair.
Not for commercial purposes without permission
Welcome to the QQ Group Discussion: android Development Alliance:272209595
In android, what are the setTag () and getTag () Methods of View used?
Set and obtain tags. Generally, you cannot directly obtain or set the tag. You can use these two set and get methods to obtain and set the tag, which will be frequently used in future programming, prevents users from directly modifying data
For example, if you write a class that contains your age and you do not want others to modify it, you can write it as private. If you want to modify it, you can call set () and get () in the program () two methods
A problem with the setTag () method and getTag () of Android
All of your operations are done in the getView method. You have specified convertView to bind a TextView. Of course, you need to make a forced type conversion (TextView) for the Tag in convertView)