有時需要根據資源名獲取對應資源也就是獲取對應資源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....