2

我已将图像名称(例如“Image1.png”)存储在JSON文件中。我已经使用JSONParser. 但问题是我无法在ImageView.

这是我写的代码:

ImageView imageView = (ImageView)findViewById(R.id.imageViewer);
for (int i = 0; i < posts.length(); i++) {
    JSONObject c = posts.getJSONObject(i);
    String varImage = c.getString(TAG_IMAGE);
    int resId = getResources().getIdentifier(varImage, "drawable" , getPackageName());                      
    imageView.setImageResource(resId);
    //code to add data in hash map
}
4

3 回答 3

1

你可以使用下面的代码来获取drawable id:

try {
    Class res = R.drawable.class;
    Field field = res.getField("drawableName"); //Here you put your image name getting from json file
    int drawableId = field.getInt(null);
}
catch (Exception e) {
    Log.e("MyTag", "Failure to get drawable id.", e);
}

获取drawable id后,就可以设置drawable为ImageView了。

于 2013-01-03T10:17:50.190 回答
1

这必须有效。

ImageView imageView = (ImageView)findViewById(R.id.imageViewer);
for (int i = 0; i < posts.length(); i++) {
    JSONObject c = posts.getJSONObject(i);
    String varImage = c.getString(TAG_IMAGE).substring(0, c.getString(TAG_IMAGE).lastIndexOf('.');
    int resId = getResources().getIdentifier(varImage, "drawable" , getPackageName());                      
    imageView.setImageResource(resId);
    //code to add data in hash map
}
于 2013-01-03T13:12:14.950 回答
0

尝试使用以下代码,让我知道它是否适合您。

 imageview= (ImageView)findViewById(R.id.imageView);

for (int i = 0; i < posts.length(); i++) {

String varImage = c.getString(TAG_IMAGE);

 String uri = "@drawable/"+ "varImage";

int imageResource = getResources().getIdentifier(uri, null, getPackageName());


Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);
}
于 2013-01-03T12:50:59.630 回答