2011-04-28 86 views
1

如何以編程方式將附加信息附加到按鈕上?我可以mButton.setText(「新文本」)來更改文本,但是我希望能夠添加更多的字段,以便當您單擊按鈕時,您可以獲取這些額外的字段並使用數據。我該怎麼做?使用按鈕存儲附加信息

回答

7

使用View.setTag(INT鍵,對象標記)字段和方法。

您可以稍後使用getTag(int key)檢索它。

在你的XML:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <item type="id" 
     name="string_key" /> 
    <item type="id" 
     name="boolean_key" /> 
</resources> 

在您的代碼:

//I'd like to store String s and Boolean b in the button. 
button.setTag(R.id.string_key, s); 
button.setTag(R.id.boolean_key, b); 

//Now, I'd like to retrieve the data in new fields. 
String new_s = (String) button.getTag(R.id.string_key); 
Boolean new_b = (Boolean) button.getTag(R.id.boolean_key); 
+0

當我嘗試時,我得到一個IllegalArgumentStatement,「密鑰必須是特定於應用程序的資源ID」。 – Roger 2011-04-28 15:44:45

+0

我的錯誤!該ID需要在xml中聲明以確保它是唯一的。有關詳細信息,請參閱http://developer.android.com/guide/topics/resources/more-resources.html#Id「 – Cephron 2011-04-28 15:55:33

+0

另外,如果您只需要存儲一個字段,則可以使用setTag(Object tag)和getTag() - 但你似乎想要存儲多個字段,這就是爲什麼需要id。 – Cephron 2011-04-28 15:57:31

1

你總是可以擴展Button類,並添加你需要

+0

請不要這樣做。或者至少不要讓我繼承你的代碼,並且必須維護和修復它。 – 2011-04-28 15:37:00

0

您可以使用Tag屬性。給它分配一個字符串[如果你有多個值使用管道字符(|)並稍後分割]或者你可以分配一個對象。