setTag () 是 Android 的 View 類中很有用的一個方法,可以用它來給控件附加一些信息,在很多場合下都得到妙用。我們可以看到 setTat() 有兩個方法重載,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中添加
使用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();
就能取到值了!
本文详细介绍了Android View类中的setTag方法,讨论了如何避免IllegalArgumentException,尤其是在使用自定义key时。重点讲解了如何通过资源ID保证key的唯一性,并演示了如何设置并获取多个tag。
2万+

被折叠的 条评论
为什么被折叠?



