Retrieve Resource Ids Using Resource Names
Accessing resources such as strings and drawables by their names instead of their integer IDs is sometimes necessary.
Method:
To achieve this, use the getIdentifier() method of the Resources class. The following code sample demonstrates obtaining a drawable resource ID by its name:
int drawableResourceId = getResources().getIdentifier("nameOfDrawable", "drawable", getPackageName());
This method can also be used to obtain IDs for other resource types, such as strings and UI elements:
// String resource int stringResourceId = getResources().getIdentifier("nameOfString", "string", getPackageName()); // UI element ID int viewId = getResources().getIdentifier("nameOfView", "id", getPackageName());
Caution:
Note that using this method for resource retrieval is relatively slow, so it should be used sparingly. For performance-sensitive applications, it's recommended to use integer IDs instead.
Reference:
Resources.getIdentifier(String name, String defType, String defPackage) documentation: https://developer.android.com/reference/android/content/res/Resources#getIdentifier(java.lang.String, java.lang.String, java.lang.String)
The above is the detailed content of How Can I Get Android Resource IDs Using Their Names?. For more information, please follow other related articles on the PHP Chinese website!