What is the main purpose of setTag() getTag() methods of View?,settaggettag

來源:互聯網
上載者:User

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中的應用。 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.