【问题标题】:Set Android Image According to string根据字符串设置Android Image
【发布时间】:2016-08-03 00:39:25
【问题描述】:

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

... 
... 
...

【问题讨论】:

  • 你不能像那样比较字符串,用这个改变 if(catString.equals("image1")) { // 做你的事情 }
  • 我认为您应该将这 100 张图像存储在您的服务器上并返回这些图像的 url,然后相应地设置该图像

标签: android android-drawable


【解决方案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));
}

【讨论】:

  • 我忘记了另一件事。我在drawable中有一个像“ic_image1”这样的前缀。那怎么称呼呢?
  • 查看编辑,您也可以使用例如HashMap。或者你可以在drawable名称前加上getResources().getIdentifier("ic_" + catString, "drawable", getPackageName())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多