Jonny
Jonny

Reputation: 35

Android - Getting identifier for view using string variable

I have a string variable which is the same as the identifier for a view.

I would like to use the R.id.xxx, but obviously I can't just replace the xxx with my string as the xxx is actually an int. What can I do to get around this?

Thanks!

Upvotes: 0

Views: 788

Answers (2)

olefevre
olefevre

Reputation: 4117

Nonsense. The framework obviously discourages that approach but it is possible: just use Java reflection, e.g.,

 java.lang.reflect.Field f = R.id.class.getField(name);
 int id = f == null ? -1 : (Integer)f.get(null);
 // now just use findViewById(id);

Upvotes: 1

Rasel
Rasel

Reputation: 15477

String s=getString(R.string.xxx);

Upvotes: 0

Related Questions