What is the main purpose of setTag() getTag() methods of View?,settaggettag
如題:方法setTag(),getTag()在View中起到的作用
為什麼我會找到這麼一個問題,主要原因就是,我在學習ViewHolder時遇到,當時只知道怎麼使用。在google時,發現stackoverflow上有不錯的解釋。遂翻譯一二。
源地址:http://stackoverflow.com/questions/5291726/what-is-the-main-purpose-of-settag-gettag-methods-of-view
釋疑:
比如說,你建立了很多個相似的View,你可以給你的View都各自添加一個OnClickLisener的屬性,如下所示一樣:
button1.setOnClickListener(new OnClickListener ... );button2.setOnClickListener(new OnClickListener ... ); ...
然後你需要為每一個View建立一個獨一無二的Onclick方法,即使他們相應的事件都是一樣的。就像如下。
public void onClick(View v) { doAction(1); // 1 for button1, 2 for button2, etc.}
This is because onClick has only one parameter, a 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 information from the views themselves.
enter getTag()/setTag();
button1.setTag(1);button2.setTag(2);
現在我們可以給每一個button使用相同的OnClickListener:
listener = new OnClickListener() { @Override public void onClick(View v) { doAction(v.getTag()); }};
It's basically a way for views to have memories.
這句話可以細細品味的。
目前尚未發現實際應用,但這篇文章主要因ViewHolder而起,恩對,就是ViewHolder中的setTag的應用。
想再瞭解的可以看看ViewHolder中的應用。