[英]Android dynamic variable for drawable resource
嗨,我的編碼有問題,該怎么做:
BitmapFactory.decodeResource(getResources(), R.drawable."some string");
我正在使用:
getResources().getIdentifier(img, "drawable", context.getPackageName())
,
然后顯示:
錯誤無法解決方法encodeResource(int)
從技術上講,您不能那樣做,因為“ R.drawable.XXXXX”是在編譯時生成的int。 我建議創建一個自定義枚舉,該枚舉將int與字符串相關聯,並提供一種返回給定另一個的方法。 例如:
public enum DrawableEnum {
STRING_ONE("some string", R.drawable.some_string),
STRING_TWO("another string", R.drawable.some_other_string),
STRING_THREE("third string", R.drawable.string_three);
private final String string;
private final int resId;
DrawableEnum(String string, int resId) {
this.string = string;
this.resId = resId;
}
int getResId() {
return resId;
}
String getString() {
return string;
}
int getResIdFromString(String string) {
for(DrawableEnum item : DrawableEnum.values()) {
if(item.getString().equals(string)) {
return item.getResId();
}
}
return -1;
}
}
然后這樣稱呼它:
int resId = DrawableEnum.getResIdFromString("some string");
BitmapFactory.decodeResource(getResources(), resId);
您將可以使用以下代碼獲取資源ID:
int resId = getResources().getIdentifier("some_string", "drawable", getPackageName());
BitmapFactory.decodeResource(getResources(), resId);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.