项目开发中,我们会经常使用到通过反射来获取资源id。

public static int getIdByName(Context context, String className, String name) { //className资源类型,name资源名称
        String packageName = context.getPackageName();
        Class r = null;
        int id = 0;

        try {
            r = Class.forName(packageName + ".R"); //拿到R文件Class文件
            Class[] classes = r.getClasses(); //返回类定义的公共的内部类,以及从父类、父接口那里继承来的内部类
            Class desireClass = null;

            Log.d("lololo", "getIdByName() returned: " +  Arrays.toString(classes));
            /**
             *  [class com.tencent.qcloud.timchat.R$styleable, class com.tencent.qcloud.timchat.R$style, class com.tencent.qcloud.timchat.R$string,
             *  class com.tencent.qcloud.timchat.R$raw, class com.tencent.qcloud.timchat.R$mipmap, class com.tencent.qcloud.timchat.R$layout
             */

            for (int i = 0; i < classes.length; ++i) {
                if (classes[i].getName().split("\\$")[1].equals(className)) {
                    desireClass = classes[i];
                    break;
                }
            }

            if (desireClass != null) {
                id = desireClass.getField(name).getInt(desireClass);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        return id;
    }

调用方法:

 setContentView(MyResource.getIdByName(getApplication(), "layout", "ui_activity_host_login"));