如何使用字符串来获取相应的图像

时间:2016-03-30 11:10:41

标签: android imageview

private int imageres[] = {
    R.drawable.desk,
    R.drawable.bed,
    R.drawable.chair,
};

private String typeofplace[] = {
    "Desk", //0
    "Bed", //1
    "Desk", //2
    "Chair", //3
    "Bed", //4
    "Chair", //5
};

for (int i = 0; i < typeofplace.length; i++) {
    //how do I get the image (int) based on the `typeofplace`:
    // MyFunction(imageres[R.drawable.{typeofplace}]);
}

陶氏我是否根据typeofplace

获取了图片(int)
MyFunction(imageres[R.drawable.{typeofplace}]);

2 个答案:

答案 0 :(得分:2)

我认为有更好的方法可以做到这一点,你不需要HashMap或带有typeofplace的字符串数组。如果您知道drawable的名称,只需使用:

int imageId = getResources().getIdentifier("desk", "drawable", getPackageName()); 

答案 1 :(得分:1)

您可以使用HashMap:

private String typeofplace[] = {
    "Desk", //0
    "Bed", //1
    "Desk", //2
    "Chair", //3
    "Bed", //4
    "Chair", //5
};

...

HashMap hm = new HashMap();
// Put elements to the map
hm.put("Desk", R.drawable.desk);
hm.put("Bed", R.drawable.bed);

for (int i = 0; i < typeofplace.length; i++) {
    doSomething(hm.get(typeofplace[i]));
}