3

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?

Community
  • 1
  • 1
Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
  • Here's an alternative approach https://stackoverflow.com/a/3217786/1358777 letting the compiler do the work for you – Alwin Kesler Mar 12 '18 at 23:55

1 Answers1

3

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^32 where N is the number of existing menu ids. If we assume a reasonable value for N, that's a pretty small number ...

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • What I was really hoping for was the ability to add an item and say "just generate a unique, non-used item id for me", and then store whatever was returned. But adding an item with Menu.NONE seems to set all the ids to Menu.NONE. – Waynn Lue Feb 19 '12 at 06:57