What is the main purpose of setTag () getTag () methods of View ?, Settaggettag
Example: Method setTag () and getTag () play a role in View
The main reason why I found such a problem is that I only knew how to use it when I learned ViewHolder. At google, I found stackoverflow had a good explanation. Translation 2.
Source Address: http://stackoverflow.com/questions/5291726/what-is-the-main-purpose-of-settag-gettag-methods-of-view
Explain:
For example, if you have created many similar views, you can add an OnClickLisener attribute for each View, as shown below:
button1.setOnClickListener(new OnClickListener ... );button2.setOnClickListener(new OnClickListener ... ); ...
Then you need to create a unique Onclick method for each View, even if their corresponding events are the same. As shown in the following figure.
public void onClick(View v) { doAction(1); // 1 for button1, 2 for button2, etc.}
This is becauseonClick
Has only one parameter,View
, And it has to get information other information from instance variables or final local variables in enclosing scopes. What we really want is to get informationFrom the views themselves.
Enter getTag ()/setTag ();
button1.setTag(1);button2.setTag(2);
Now we can use the same OnClickListener for each button:
listener = new OnClickListener() { @Override public void onClick(View v) { doAction(v.getTag()); }};
It's basically a way for views to haveMemories.
You can savor this sentence.
Currently, no practical application has been found. However, this article mainly starts with ViewHolder, which is the application of setTag in ViewHolder.
For more information, see the applications in ViewHolder.