How To Get Resource Id Dynamically In Android
Posted by admin on
July 11, 2012
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.
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.
getRestId("help", this, R.layout.class);







