Retrieving Resource ID and String in Android
In Android development, obtaining both the resource ID and the string value associated with a resource can be a common requirement. Consider the following example:
R.drawable.icon
This reference denotes a drawable resource named "icon". To pass both its ID and string representation to a method, you have several options.
Using Resources.getIdentifier()
The Resources.getIdentifier() method allows you to obtain the resource ID for a given string. Pass the string, the desired resource type (e.g., drawable), and the package name as parameters.
int resId = getResources().getIdentifier("icon", "drawable", getPackageName());
This will retrieve the ID of the "icon" drawable. However, you still need to manually retrieve the string value using getString().
Using Java Reflection
Another approach is to use Java reflection to get the resource ID and string value directly. However, this method may fail in some scenarios, such as when code/resource shrinking is enabled or when the resource name does not match the field name (e.g., for string resources).
try { Field idField = R.drawable.class.getDeclaredField("icon"); int resId = idField.getInt(null); String resString = getResources().getString(resId); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); }
Hybrid Approach
A hybrid approach can provide the best of both worlds. Pass the string value to the method, and have it internally use getIdentifier() to obtain the resource ID. This ensures that the method only receives the string, while still allowing access to both the ID and the string value.
Example:
private void processResource(String resourceName) { int resId = getResources().getIdentifier(resourceName, "drawable", getPackageName()); if (resId != 0) { // Do something with the resource ID and string value... } }
By choosing the most appropriate solution for your use case, you can effectively retrieve and utilize both the resource ID and string value in Android development.
The above is the detailed content of How to Efficiently Retrieve Resource IDs and String Values in Android?. For more information, please follow other related articles on the PHP Chinese website!