1. 程式人生 > >android關於控制元件中setTag(key,Object)的設定的相關問題

android關於控制元件中setTag(key,Object)的設定的相關問題

setTag () 是 Android 的 View 類中很有用的一個方法,可以用它來給控制元件附加一些資訊,在很多場合下都得到妙用。

我們可以看到 setTag() 有兩個方法過載,setTag(Object object) setTag(int key,Object object) 引數型別 都帶有 Object 也就是 可以儲存任何 物件資料。

下面分別介紹下相關使用方法。

----------

void setTag(Object tag)

這個方法相對簡單,如果只需要設定一個 tag,那麼直接呼叫 setTag(Object tag) 取值:view.getTag();

方法就可以輕鬆搞定。

void setTag (int key, Object tag)

官方的api文件中提到:

>“ The specified key should be an id declared in the resources of the application to ensure it is unique (see the ID resource type). Keys identified as belonging to the Android framework or not associated with any package will cause an IllegalArgumentExceptionto be thrown.”

所以丟擲 IllegalArgumentException 的原因就在於 key 不唯一,那麼如何保證這種唯一性呢?很明顯定義一個 final 型別的 int 變數和硬編碼一個值的方式都是行不通的。比如下面一個錯誤的例子:

private static final int TAG_ONLINE_ID = 1;
((Button)row.findViewById(R.id.btnPickContact)).setTag(TAG_ONLINE_ID,objContact.onlineid);
05-18 20:29:38.044: ERROR/AndroidRuntime(5453): java.lang.IllegalArgumentException: The key must be an application-specific resource id.
05-18 20:29:38.044: ERROR/AndroidRuntime(5453):at android.view.View.setTag(View.java:7704)
05-18 20:29:38.044: ERROR/AndroidRuntime(5453):at com.mypkg.viewP.inflateRow(viewP.java:518)


那如果一定需要使用多個 tag 繫結怎麼做呢?那麼這麼做,在 res/values/strings.xml 中新增

<resources>
<item type="id" name="tag_first">
</item>
<item type="id" name="tag_second">
</item>
</resources>


使用

imageView.setTag(R.id.tag_first, "Hello");
imageView.setTag(R.id.tag_second, "Success");


就這就保證了 key 值的唯一性。

取值

String tag_first=v.getTag(R.id.tag_first).tostring();


就能取到值了!