When multiple regular resource IDs are obtained, they can be obtained using the Getidentifier method.
Use the scene: when a tool class is called a. jar package, it is sometimes necessary to refer to resources in res, when resources cannot be packaged together, and resources can be obtained dynamically through the reflection mechanism.
public class Resources int Getidentifier (string name, String Deftype, String defpackage) Return A resource identifier for The given resource name.
Param deftype: "Layout", "string", "drawable", "style", "Color", "array"
Parameters
| Name |
The name of the desired resource. |
| Deftype |
Optional default resource type to find, if "type/" was not included in the name. Can is null to require an explicit type. |
| Defpackage |
Optional default Package to find, if ' package: ' is not included in the name. Can is null to require a explicit package. |
Returns
- int the associated resource identifier. Returns 0 If no such resource was found. (0 is a valid resource ID.)
From:http://developer.android.com/reference/android/content/res/resources.html
public static int Getdrawableid (Context paramcontext, String paramstring) { return paramcontext.getresources (). Getidentifier (paramstring, "drawable", Paramcontext.getpackagename ()); }
For this method, the official does not recommend:
Note:use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
A better solution is to use reflection from another blog post.
http://www.liaohuqiu.net/cn/posts/android-get-resource-id-by-string/
Example code:
public static int Getresid (String variableName, class<?> c) { try { Field IDfield = C.getdeclaredfield (vari Ablename); Return Idfield.getint (IDfield); } catch (Exception e) { e.printstacktrace (); return-1;} }
Use:
int id = resourceman.getresid ("icon", R.drawable.class);
This efficiency is said to be 4 times times higher than the first type.
Android gets a regular resource ID solution