setTag ()
是 Android 的 View 类中颇有用的一个方法,能够用它来给控件附加一些信息,在不少场合下都获得妙用。咱们能够看到 setTat() 有两个方法重载,setTag(Object object)
和 setTag(int key,Object object)
参数类型 都带有 Object 也就是 能够保存任何 对象数据。
下面分别介绍下相关使用方法。java
这个方法相对简单,若是只须要设置一个 tag,那么直接调用 setTag(Object tag)
取值:view.getTag();
方法就能够轻松搞定。android
官方的api文档中提到: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.”app
因此抛出 IllegalArgumentException
的缘由就在于 key 不惟一,那么如何保证这种惟一性呢?很明显定义一个 final 类型的 int 变量和硬编码一个值的方式都是行不通的。好比下面一个错误的例子:ide
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 值的惟一性。spa
String tag_first=v.getTag(R.id.tag_first).tostring();
就能取到值了!code
做者:老林不跌面儿
连接:https://www.jianshu.com/p/2df2675b516d
来源:简书
著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。xml