android 应用通过自定义资源名获取资源

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuxingchong/article/details/81481520

有时需要根据资源名获取对应资源也就是获取对应资源id,通过资源id再获取对应资源,因为资源id一般是自动生成我们不会取直接取值来用,所有下面的方法可以获取到资源id从而获取对应资源.

//对应图片资源数组
private static final String[] RES_ICON_NAME = {
        "com_android_systemui",
        "com_cloudminds_launcher3",
        "com_android_wallpaper_livepicker",
        "com_android_systemui_lookscreen",
};
//对应字符串资源数组
private static final String[] APP_NAME = {
        "statusBar",
        "launcher",
        "wallpaper",
        "lookscreen",
};

//关键点通过下面方式获取id,drawable资源
public static int getResIconId(Context context, String iconName){
    return context.getResources().getIdentifier(iconName, "drawable", context.getPackageName());
}

//字符串资源
public static int getResNameId(Context context, String iconName){
    return context.getResources().getIdentifier(iconName, "string", context.getPackageName());
}

//实际使用地方
for(int i = 0;i < APP_NAME.length;i++){
    String name = 
       context.getResources().getString(getResNameId(context,APP_NAME[i]));
    Drawable drawable = 
       context.getDrawable(getResIconId(context,RES_ICON_NAME[i])));
 }

可以根据不同的需要替换掉string,drawable,dimen....

猜你喜欢

转载自blog.csdn.net/zhuxingchong/article/details/81481520
今日推荐