(Android) about getting data in resource file R
We usually useContext. getResources (). getIdentifier (name, type, context. getPackageName ())To obtain data in R. java.
Type -- R internal class names, such as "drawable", "string", "color", "dimen", "layout", etc, this is also a common data type for the interface.
Name -- the static variable name in the R internal class, such as "appname", which are defined by the user in the xml file, including the xml file name in the layout and drawable files.
The last parameter is the package name of the apk.
Actually why?Context. getResources (). getIdentifierTo obtain the resource value, it is very simple. When developing your own sdk, because your resource files and jar packages are available to others, this method is used to obtain the corresponding resource value on the interface.
Go back to the topic, because the attr custom attribute is used in the development of the control, and a problem is found during the development, that isStyleableCannot be usedContext. getResources (). getIdentifierThe result is always 0, andStyleableThe array data is also included, so we finally use the java reflection method to obtain the data. Code:
/**
* For data that cannot be obtained by context. getResources (). getIdentifier, or an array
* Resource reflection Value
* @ Paramcontext
* @ Param name
* @ Param type
* @ Return
*/
Private static Object getResourceId (Context context, String name, String type ){
String className = context. getPackageName () + ". R ";
Try {
Class Cls = Class. forName (className );
For (Class ChildClass: cls. getClasses ()){
String simple = childClass. getSimpleName ();
If (simple. equals (type )){
For (Field field: childClass. getFields ()){
String fieldName = field. getName ();
If (fieldName. equals (name )){
System. out. println (fieldName );
Return field. get (null );
}
}
}
}
} Catch (Exception e ){
E. printStackTrace ();
}
Return null;
}
/**
* Context. getResources (). getIdentifier cannot obtain styleable data.
* @ Paramcontext
* @ Param name
* @ Return
*/
Public static int getStyleable (Context context, Stringname ){
Return (Integer) getResourceId (context, name, "styleable"). intValue ();
}
/**
* Get the ID number array of styleable
* @ Paramcontext
* @ Param name
* @ Return
*/
Public static int [] getStyleableArray (Context context, String name ){
Return (int []) getResourceId (context, name, "styleable ");
}