android在设计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常量,如下:

            

使用如下:

  imageView.setTag(R.id.tag_first, "Hello");  imageView.setTag(R.id.tag_second, "Success");

以上就是对Android setTag方法的key问题的解决办法,谢谢大家对本站的支持!

更多相关文章

  1. Android(安卓)退出应用程序问题
  2. [置顶] android 如何在自定义对话框中获取edittext中的数据
  3. Android实现可使用自定义透明Dialog样式的Activity完整实例
  4. Android(安卓)面试笔试集锦 --- 基本知识点 整理版
  5. Android广播接收器(三)
  6. Android有效获取状态栏(StatusBar)高度的方法
  7. android 自定义锁屏
  8. Android(安卓)SharedPreferences 首次运行引导界面
  9. 深入讲解Android(安卓)MVP框架,附一个很屌的实现MVP架构的开源库T

随机推荐

  1. Android 面试题汇总及解答
  2. Android UI 设计最佳实践
  3. 为什么 Android 8.0 注册的广播接收不到
  4. Android实现LED灯显示效果
  5. Android 发布应用到市场
  6. 【极客青年】电脑专用的安卓系统-凤凰系
  7. 使用Git之后出现android library引用失败
  8. android之获取设备唯一标识符
  9. android UI进阶之android中隐藏的layout
  10. 文章:开发者眼中的Android手机平台