English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
When designing the View class, Android designed a setTag to store some auxiliary information./The getTag method. This reminds me of the Tag existing in each Control in Winform design.
Today, I want to talk about a pit I encountered with setTag in my recent learning of Android. Generally, we only need to use the setTag method with a unique parameter. But sometimes we need to store multiple pieces of data, so in this case, we need to use the overloaded version with a key.
The document describes: '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 IllegalArgumentException to be thrown.'
This explains that it is necessary to ensure the uniqueness of the key, but if we use Java constants to define the key (private static final int TAG_ID = 1;) You will still encounter the following error:
java.lang.IllegalArgumentException: The key must be an application-specific resource id
The correct solution is:
In res/values/Define this key constant in strings.xml as follows:
<resources> <item type="id" name="tag_first"></item> <item type="id" name="tag_second"></item> </resources>
Use as follows:
imageView.setTag(R.id.tag_first, "Hello"); imageView.setTag(R.id.tag_second, "Success");
That's all for the solution to the key problem of Android setTag method, thank you all for your support to this site!
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please report any infringement by sending an email to codebox.com (replace # with @ in the email address), and provide relevant evidence. Once verified, this site will immediately delete the infringing content.