Android 反射方法调用R文件,解除包名依赖

来源:互联网 发布:郑和热水瓶 知乎 编辑:程序博客网 时间:2024/05/17 02:32

如果是R.id 或者R.drawable ,可以通过  context.getResource().getIdentifier(name,"id",context.getPackageName())  这种方式获得ID,

经过测试发现R.styleable R.attr 获取不到,这种情况可以通过反射的方法



/** *  * @param context * @param type * @param name * @return */public static Object getResourceData(Context context, String type, String name) {try {Class<?> arrayClass = getResourceClass(context, type).getClass();Field intField = arrayClass.getField(name);return intField.get(arrayClass);} catch (Exception e) {e.printStackTrace();}return null;}private static HashMap<String, Object> ResourceClass = new HashMap<String, Object>();private static Object getResourceClass(Context context, String type) {if (ResourceClass.containsKey(type)) {return ResourceClass.get(type);} else {try {Class<?> resource = Class.forName(context.getPackageName() + ".R");Class<?>[] classes = resource.getClasses();for (Class<?> c : classes) {int i = c.getModifiers();String className = c.getName();String s = Modifier.toString(i);if (s.contains("static") && className.contains(type)) {ResourceClass.put(type, c.getConstructor().newInstance());return ResourceClass.get(type);} else {continue;}}} catch (Exception e) {e.printStackTrace();}}return null;}

这种方法兼容R文件里的所有内容,取出来之后类型强制转换一下就好了

(int[]) getResourceData(context, "styleable", "Setting")

(Integer) getResourceData(context, "id", "title")

阅读全文
0 0
原创粉丝点击