转自http://www.cnblogs.com/whitewolf/p/3999773.html

ndroid在设计View类时,为了能储存一些辅助信息,设计一个一个setTag/getTag的方法。这让我想起在Winform设计中每个Control同样存在一个Tag。

今天要说的是我最近学习android遇见的setTag的坑。一般情况下我们只需要使用唯一参数的setTag方法。但有时我们需要存储多个数据,所以这个时候我们就需要使用带key的重载。

文档是描述:“ 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.”

这里说明必须保证key的唯一,但是如果我们使用java常量定义key(private static final int TAG_ID = 1;)这样你任然会遇见如下错误:

java.lang.IllegalArgumentException: The key must be an application-specific resource id

正确的解决方案是:

在res/values/strings.xml中定义这个key常量,如下:

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

更多相关文章

  1. MTK Android(安卓)紧急号码修改
  2. Android(安卓)Handler,Looper,MessageQueue关系(讲解比较透彻的)
  3. android Bitmap如何保存成为一个bmp文件
  4. Android(安卓)通知栏Notification的整合 全面学习 (一个DEMO让你
  5. Android中屏蔽 电源键长按、Home键、Home长按
  6. Android高频面试专题 - 基础篇(一)Activity
  7. 常用控件的使用方法(参考书籍'第一行代码')
  8. Android动态化方案
  9. android 访问webservice问题

随机推荐

  1. [Android(安卓)Pro] 关于Android的HTTP客
  2. 详细解读Android中的搜索框(四)—— Search
  3. Android实现微信底部导航条
  4. permission和uses-permission的区别
  5. 自定义menu替代TabHost中的TabWidget
  6. Android(安卓)背景渐变 渐变背景 shape
  7. android am命令
  8. android shape的用法总结
  9. [Android] 环境配置之基础开发环境(SDK/An
  10. Android联系人3--联系人分组相关