When passing a resource ID to a method, it's often desirable to access both the ID and the corresponding string. For instance, consider the "icon" resource:
R.drawable.icon
To obtain both the ID and the string "icon", several approaches can be explored:
One solution involves utilizing the Resources.getIdentifier() method:
int resID = getResources().getIdentifier("icon", "drawable", getPackageName()); String iconString = "icon";
However, recent research has indicated that Resources.getIdentifier() can be less efficient than using reflection.
Alternatively, you can employ the following reflection-based code:
public static int getResId(String resName, Class<?> c) { try { Field idField = c.getDeclaredField(resName); return idField.getInt(idField); } catch (Exception e) { e.printStackTrace(); return -1; } }
To utilize this method for the "icon" resource:
int resID = getResId("icon", R.drawable.class); // or other resource class String iconString = "icon";
Although this reflection approach may be more efficient, it's important to note potential drawbacks. In a release build with code/resource shrinking enabled, this solution may fail. Additionally, it might not work in cases where the string name differs from the expected resource name format.
The above is the detailed content of How to Efficiently Get an Android Resource ID from its String Name?. For more information, please follow other related articles on the PHP Chinese website!