Android 不得不知 之 Tag 妙用

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中添加

<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();

就能取到值了!

    原文作者:老林不跌面儿
    原文地址: https://www.jianshu.com/p/2df2675b516d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞