25

In the Java code of an Android project if you want the reference for a view resource you can do something like:

View addButton = findViewById(R.id.button_0);

In the above R.id.button_0 is not a String. Is it possible to dynamically refer to a resource by a string, such as "R.id.button_0"?

I'd like to refer to a button by "R.id.button_%i" where %i is replaced by some valid index.

Ken
  • 30,811
  • 34
  • 116
  • 155

2 Answers2

56
int resID = getResources().getIdentifier("button_%i",
    "id", getPackageName());
View addButton = findViewById(resID);

where %i is replaced by some valid index.

The getResources() method belongs to the Context class, so you can use that directly from an Activity. If you are not inside an activity, then use a context to access: (myCtxt.getResources()).

Alan Moore
  • 6,525
  • 6
  • 55
  • 68
Cristian
  • 198,401
  • 62
  • 356
  • 264
  • 3
    Note this is going to be significantly slower than using the ID directly. – hackbod Jan 19 '11 at 00:49
  • Thanks, just what I was looking for. Btw, I fixed a compile error in this code sample. – Alan Moore Jun 11 '12 at 15:23
  • @hackbod why will it be slower? if you, or someone else, could point to a doc reference for your assertion, it would be great. – Vinay W Aug 13 '13 at 05:34
  • It is slower because instead of accessing the ID (which is just a plain Java constant), it will call a bunch of methods that will likely use reflection in order to obtain the constant value. See also http://stackoverflow.com/questions/3502674/why-reflection-is-slow – Cristian Aug 13 '13 at 17:55
  • @VinayWadhwa In my experience, using this in a loop caused such poor performance it is not acceptable. – ThomasW Jun 28 '16 at 03:54
  • using of getIdentifier is not recommended anymore – Darksymphony Jan 26 '23 at 16:04
4

You could try putting all the ids you want in an array and then using that array to dynamically refer to your resources instead.

jsonfry
  • 2,067
  • 2
  • 15
  • 16
  • This could be a good approach for some special occasions (when the name of the resources changes or the order is complex); otherwise I think it's not the better way to do it. Some times you will end up with a huge array which makes your code look smelly. – Cristian Jan 18 '11 at 23:35
  • @cristian it does indeed make horrible nasty code. Where i've done this in the past i've shoved it in its own static class. But your approach seems somewhat nicer ;) – jsonfry Jan 18 '11 at 23:52