Android setTag方法的key问题

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常量,如下:

    <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");
本博客已经转移个人博客破狼,也有有部分更新,但不保证及时维护,如果你希望及时看到本人的新日志,那请订阅破狼-RSS或者关注微信订阅号"shuang_lang_shuo",且听雪狼和破狼两狼为你ng说道:
双狼说


作者:破  狼 
出处:http://www.cnblogs.com/whitewolf/ 
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。该文章也同时发布在我的独立博客中-个人独立博客博客园--破狼51CTO--破狼

原文:http://www.cnblogs.com/whitewolf/p/3999773.html

原文地址:https://www.cnblogs.com/veins/p/4381908.html