根据资源名称动态获取资源id的两种方式

通常情况下我们使用R.xxx的方式引用资源,在某些情况下需要根据资源的name来获取资源的id,查了下资料,目前主要有两种方式,这里总结记录一下:

第一种,通过反射来获取

例如,根据name获取drawable资源:

    private int getDrawableId(String drawableName) {
        try {
            Field field = R.drawable.class.getField(drawableName);
            return field.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

根据name获取String资源:

    private int getStringId(String strName) {
        try {
            Field field = R.string.class.getField(strName);
            return field.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

基本上需要什么资源,直接调用对应的R.xxx.class.getField去获取即可。

在某些情况下,代码中访问不到R文件,无法直接引用R类,这时可以通过Class.forName的方式获取:

    public static int getResourceId(String packageName, String className, String idName) {
        int id = 0;
        try {
            Class<?> cls = Class.forName(packageName + ".R$" + className);
            id = cls.getField(idName).getInt(cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

调用:

 //获取R.drawable.ic_arrow
 int id = getResourceId("com.test.simlpe", "drawable", "ic_arrow");

其中第二个参数就是平时R.xxx的R后面那个类的字符串。

第二种,使用Resources 类的方法获取

android的 Resources 类中提供了一个 getIdentifier 方法可以直接获取到资源id值,使用更加方便。

例如,根据name获取drawable资源:

    public static int getDrawableResByName(Context context, String imgName) {
        Resources resources = context.getResources();
        return resources.getIdentifier(imgName, "drawable", context.getPackageName());
    }

根据name获取String资源:

    public static int getStringResByName(Context context, String strName) {
        Resources resources = context.getResources();
        return resources.getIdentifier(strName, "string", context.getPackageName());
    }

注意getIdentifier的第二个参数一般都是小写的,如string、drawable、color、dimen等,写错了就无法获取到了。

发布了96 篇原创文章 · 获赞 57 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/lyabc123456/article/details/86714803