Brandon Brandon -3 years ago 79
Android Question

Checking to see if an ID exists in resources (

So, I have code that's generating ID's for a number of elements using an AtomicInteger that's set by default at Integer.MAX_VALUE and is decremented from there with each view that gets assigned an ID. So the first view with a generated ID would be

Integer.MAX_VALUE - 1
, the second would be
Integer.MAX_VALUE - 2
, etc. The problem I'm afraid of is a collision with IDs generated by Android in

So my question is how can I detect if an ID is already in use and skip it when I'm generating the IDs. I'm only generating at most 30 IDs so this isn't a huge priority nut I'ld like to make this as bug free as possible.

Answer Source

The following code will tell you if the identifier is an id or not.

static final String PACKAGE_ID = ""
int id = <your random id here>
String name = getResources().getResourceName(id);
if (name == null || !name.startsWith(PACKAGE_ID)) {
    // id is not an id used by a layout element.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download