The suggested way of implementing menus in Android is to use XML to define a menu, which works for static menus. I’m currently trying to create a dynamic sub-menu, though, and I’d like to associate unique item ids with each of the items in a submenu so that I can store metadata with them.
There’s an answer here that suggests using an autoincrementing id, but I also have existing item ids being used for other parts of the menu that look like this (in R.java)
public static final int item2=0x7f070002;
I’m sure I can start at id = 1 and then increment, but if the id generation scheme ever changes for R.java, I’m worried I’ll start seeing collisions. Is there a better way of generating these ids? Or do I just need to keep track of the max id, then start incrementing from there?
The “correct” solution would be to traverse the objects that describe the menus to find all of the ids that are in use, then use a different one.
But, if you are prepared to live with a small chance of a problem, you could simply generate your dynamic menu ids using a random number generator. Assuming you have 32 bit ids, the probablility of a single collision menu item colliding is
N / 2^32whereNis the number of existing menu ids. If we assume a reasonable value forN, that’s a pretty small number …