Usually we use the context.getresources (). Getidentifier (name, Type,context.getpackagename ()) method to get to R.java Data in the.
type--R The internal class name, such as "drawable", "string", "Color", "dimen", "layout" , etc., This is also the type of data that we commonly use to obtain about interfaces.
name-the static variable names in theR inner class, such as "AppName" , are defined in the XML file by the user, including The file name of the XML in the layout,drawable file.
The last parameter is the package name of the apk .
In fact, why use context.getresources (). Getidentifier to get the value of a resource, very simply, when developing your own SDK , because your resource files and jar The package is for other people to use, which naturally uses this method to obtain the corresponding value of the resource in the interface.
Then back to the point, because in the development of their own control, the use of attr custom properties, during the discovery of a problem, that is, the value of styleable can not use context.getresources (). Getidentifier to get, the result is always 0, and the styleable also includes the array data, so the last is to use the Java reflection method to obtain. On the code:
/**
* for context.getresources (). Getidentifier Data not available , or 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 Unable to get data for styleable
* @paramcontext
* @param name
* @return
*/
public static int Getstyleable (context context, Stringname) {
Return ((Integer) Getresourceid (context, name, "Styleable")). Intvalue ();
}
/**
* get styleable 's ID numbers Group
* @paramcontext
* @param name
* @return
*/
public static int[] Getstyleablearray (Context context,string name) {
Return (int[]) Getresourceid (context, name, "styleable");
}
<Android> about getting data from resource file R