Android and getting a view with id cast as a string
Asked Answered
T

2

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.

Thad answered 18/1, 2011 at 23:7 Comment(0)
V
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()).

Vagabond answered 18/1, 2011 at 23:13 Comment(6)
Note this is going to be significantly slower than using the ID directly.Micrography
Thanks, just what I was looking for. Btw, I fixed a compile error in this code sample.Ryley
@Micrography why will it be slower? if you, or someone else, could point to a doc reference for your assertion, it would be great.Lema
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 https://mcmap.net/q/276827/-why-is-reflection-slowVagabond
@VinayWadhwa In my experience, using this in a loop caused such poor performance it is not acceptable.Asyllabic
using of getIdentifier is not recommended anymoreLiebfraumilch
R
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.

Resorcinol answered 18/1, 2011 at 23:14 Comment(2)
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.Vagabond
@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 ;)Resorcinol

© 2022 - 2024 — McMap. All rights reserved.