根据字符串设置 Android 图片

Set Android Image According to string

我的可绘制对象中有 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));
    }

... 
... 
...

尝试这样的事情:

// 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));
}