android 應用通過自定義資源名獲取資源

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章