tags:

views:

690

answers:

2

Yes, I know you need a unique resource id when calling the version of these functions that requires a key, but I cannot for the life of me figure out how to create a resource id that can be used in this way. A final variable in my class wont work and neither will a hard coded value. Both threw an IllegalArgumentException. So what gives, how do you use these methods?

Spara

+2  A: 

From the Javadoc:

The specified key should be an id declared in the resources of the application to ensure it is unique.

So you can't just make up values and place them in a local variable.

Every resource you create whether it's a string (R.string.*), or a layout (R.layout.*) or an individual View (R.id.*) can have an ID. This is something you must be doing already.

If you do need to store multiple objects against a single View, then you need to use the R.id variant as a key, like someView.setKey(R.id.my_key_1, someObject).

Christopher
Also, note that I got complaints from the core Android team for using the indexed form of `getTag()` and `setTag()`. Those are designed to be used by libraries or other reusable components (which cannot blindly call the regular `getTag()`/`setTag()` because they might conflict with the reuser of the code). If you are writing such a library, you're fine. If you are writing an ordinary Android application, use the regular non-indexed `getTag()`/`setTag()` methods, just with a collection of some form (e.g., `HashMap`) if you need to hold more than one value.
CommonsWare
Yeah, that sounds reasonable. I hadn't even heard of the indexed version before and couldn't think of any particular reason to have multiple objects stored per view.
Christopher
The correct way to use the indexed version of getTag()/setTag() is to use resource ids, as in R.id. Do not use R.string or R.layout as keys.
Romain Guy
Thank you CommonsWare. For some reason I had only thought of the get/setTag functions as one tag = one value. Using setTag with an object which itself contains multiple values will work perfectly.
Sparafusile
+4  A: 

To create resource ID, which can be used identically to the ones you set within XML (with @+id), add

<resources>
    <item type="id" name="myId"/>
</resources>

in XML in res/values/.

Dimitar Dimitrov