假设您在drawable
文件夹中有一些图像:
drawable
image_name_1
image_name_2
image_name_3
image_name_4
...
将图像名称放入JSON中:
[
{
"some_field_1": "some_value_1",
"some_field_2": "some_value_2",
"some_field_3": "some_value_3",
...
"image_name": "image_name_1"
},
{
"some_field_1": "some_value_1",
"some_field_2": "some_value_2",
"some_field_3": "some_value_3",
...
"image_name": "image_name_2"
},
{
"some_field_1": "some_value_1",
"some_field_2": "some_value_2",
"some_field_3": "some_value_3",
...
"image_name": "image_name_3"
},
...
]
从JSON中获取名称并加载可绘制资源:
JSONArray data;
Context context;
Resources resources = context.getResources();
for (int i = 0; i < data.length(); i++) {
String imageName = data.getJSONObject(i).getString("image_name");
final int resourceId = resources.getIdentifier(imageName, "drawable", context.getPackageName());
Drawable drawable = resources.getDrawable(resourceId);
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
}
更新
将图像资源id存入HashMap中
...
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
JSONArray data;
Context context;
Resources resources = context.getResources();
for (int i = 0; i < data.length(); i++) {
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", "Country : " + countries[i]);
hm.put("cur","Currency : " + currency[i]);
String imageName = data.getJSONObject(i).getString("image_name");
final int resourceId = resources.getIdentifier(imageName, "drawable", context.getPackageName());
hm.put("flag", Integer.toString(resourceId) );
aList.add(hm);
}
switch
语句。如果图像是JSON对象的一部分,则可以考虑对图像进行Base64编码/解码。 - Vince Blas