setTag ()
是 Android 的 View 類中很有用的一個方法,可以用它來給控件附加一些信息拱撵,在很多場合下都得到妙用篷店。我們可以看到 setTat() 有兩個方法重載昔园,setTag(Object object)
和 setTag(int key,Object object)
參數(shù)類型 都帶有 Object 也就是 可以保存任何 對象數(shù)據(jù)扁瓢。
下面分別介紹下相關(guān)使用方法。
void setTag(Object tag)
這個方法相對簡單,如果只需要設置一個 tag坤溃,那么直接調(diào)用 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();
就能取到值了!