一.简介
setTag可以为控件增加一些附加信息,他是android中很有用的一个方法,setTag有两个方法,
1.setTag(Object tag)方法比较简单,只需要放入你要设置的信息即可.
2.setTag(int key,Object tag);如果你要添加的不是单独的一种信息,那么就要用第二种方法,第一个参数是key值,在获取对应信息的时候,需要以key来获取,第二参数和第一种一样,
之所以报出这个异常,我也搜索了一些博客和资料:
官方的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不唯一,那么如何保证这种唯一性呢?定义一个int变量方式是错误的。
二.解决方法
如果要添加多个tag的话,就需要先在res/values/ids.xml中添加id,然后在代码中通过R.id.xxx的方式设置tag,
如果你的项目没有ids的文件,请新建一个以ids为名称的xml文件然后:
<resources>
<item type="id" name="tag_first"></item>
<item type="id" name="tag_second"></item>
</resources>
以上面的格式添加你的id,后面在代码中设置:
tv.setTag(R.id.tag_first, "Hello");
tv.setTag(R.id.tag_second, "Success");
在获取信息的时候:
tv.getTag(R.id.tag_first);
获取