Share the post "How To Get Resource Id Dynamically In Android"
In Android, we normally use the R class in order to gain access to the drawable, layout, string (and others) variables.
I made this helper method to get a resource id dynamically. However, if you have no need for this, it is a better option to use the R class directly as the search operation is quicker compared to this.
|
1 2 3 4 5 6 7 8 9 |
public static int getResId(String variableName, Context context, Class<?> c) { try { Field idField = c.getDeclaredField(variableName); return idField.getInt(idField); } catch (Exception e) { e.printStackTrace(); return -1; } } |
Let us say, you have an XML file named help.xml in your res/layout/ folder. To use the method, do it like this.
|
1 |
getRestId("help", this, R.layout.class); |