如何从JSON数组动态地向ImageView添加图像

4

我想从存储在 JSON 文件中的链接向我的 ImageView 添加图像,该文件看起来像这样:

{
"parts":[
    {"name": "Bosch Iridium",

        ...
        ...
        ...

        "image": "R.drawable-hdpi.plug_boschi"
    },

现在我使用以下代码提取链接并显示:

try {

    jObject = new JSONObject(sJSON.substring(sJSON.indexOf('{')));
    JSONArray pluginfo = jObject.getJSONArray("parts");
    JSONObject e = pluginfo.getJSONObject(position);

    String imagefile = e.getString("image");
    Drawable image = getDrawable(imagefile);

    ImageView itemImage = (ImageView) findViewById(R.id.item_image);

    itemImage.setImageDrawable(image);

        } catch (JSONException e) {
        e.printStackTrace();
        }
    }

我相信这部分是正确的。

ImageView itemImage = (ImageView) findViewById(R.id.item_image);

itemImage.setImageDrawable(image);

但我需要帮助的部分是从JSON数组中获取链接,以便我可以显示它。

2个回答

10

您需要先从JSON字符串中获取资源ID。

String imagefile = e.getString("image");
String resName = imagefile.split("\\.")[2]; // remove the 'R.drawable.' prefix
int resId = getResources().getIdentifier(resName, "drawable", getPackageName());
Drawable image = getResources().getDrawable(resId);

0
你想要做的是查看资源类。
getIdentifier (String name, String defType, String defPackage);

所以,基本上解析对象以查找文本plug_boschi,并调用:
int resid=Context.getResources().getIdentifier ("plug_boschi", "drawable", null);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接