2012-11-19 28 views
4

我想將圖像從存儲在一個JSON文件的鏈接看起來像這樣添加到我的iamgeview添加到ImageView的:如何將圖像動態地從一個JSON陣列

{ 
"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); 

但我需要與T幫助他是從JSON數組中獲取鏈接的部分,因此我可以顯示它。

回答

9

您需要先從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

這工作很容易,謝謝! –

0

你想要做的是看Resources類。

getIdentifier (String name, String defType, String defPackage); 

所以,基本上解析對象查找的文字plug_boschi,並呼籲:

int resid=Context.getResources().getIdentifier ("plug_boschi", "drawable", null);