根据字符串设置Android Image

时间:2016-04-12 11:58:20

标签: android android-drawable

我的drawable中有超过100张图片。它基本上是一个类别。我从服务器调用数据,其中列包括类别。我的图像命名为cat_image1,cat_image2,cat_image3等。服务器分别将相应的srting发送为Image1,Image2,Image3等。我认为这不是我正在做的事情

String catString = someJSONObject.getString(Config.POI_CATEGORY);

if (catString == "image1") {
    someView.setImage(getResources().getDrawable(R.mipmap.image1));
}

else if (catString == "image2") {
        someView.setImage(getResources().getDrawable(R.mipmap.image2));
    }

else if (catString == "image3") {
        someView.setImage(getResources().getDrawable(R.mipmap.image3));
    }

... 
... 
...

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

// catString = cat -> R.drawable.cat
int imageId = getResources().getIdentifier(catString, "drawable", getPackageName());
someView.setImage(imageId));

如果你需要一个前缀,请使用:

// catString = cat -> R.drawable.ic_cat
int imageId = getResources().getIdentifier("ic_" + catString, "drawable", getPackageName());
someView.setImage(imageId));

您也可以使用HashMap:

HashMap<String, Integer> hm = new HashMap<>();
// Put elements to the map
hm.put("cat", R.drawable.ic_some_cat_image);
hm.put("other cat", R.drawable.ic_other_cat);

for (int i = 0; i < typeofplace.length; i++) {
    // You might want to check if it exists in the hasmap
    someView.setImage(hm.get(catString));
}
相关问题