如何从 json 文件中根据图像名动态的获得图像?

我在json文件中储存了图像名,例如:"Image1.png"。我使 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
}

使用代码:

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
}

使用下面的代码获取 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后,然后在 ImageView 设置 drawable。