gpt4 book ai didi

android - 本 map 片通过android中的本地json

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:50:35 26 4
gpt4 key购买 nike

我有一个本地 json,其中包含一些显示在 ListView 中的静态数据。

每个对象都应该有一个图像/ Logo ,该图像/ Logo 也显示在 ListView 中。该图像将在本地并位于可绘制文件夹中。

data/listview类似这个http://wptrafficanalyzer.in/blog/android-itemclicklistener-for-a-listview-with-images-and-text/

在本教程中,所有数据和图像都存储在数组中。我的数据存储在 JSON 中。

那么如何在 JSON 中“引用”图像或图像名称以及在创建 ListView 时如何实际访问图像?

最佳答案

假设您的 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 中获取名称并加载 drawab 资源:

    JSONArray data; // your JSON
Context context; // context
Resources resources = context.getResources();
for (int i = 0; i < data.length(); i++) {
// getting some another JSON field

// get image name from JSON
String imageName = data.getJSONObject(i).getString("image_name");

// get resource id by image name
final int resourceId = resources.getIdentifier(imageName, "drawable", context.getPackageName());

// get drawable by resource id
Drawable drawable = resources.getDrawable(resourceId);

// get bitmap by resource id
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
}

更新

将图片资源id放入HashMap

    ...
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

JSONArray data; // your JSON
Context 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]);

// get image name from JSON
String imageName = data.getJSONObject(i).getString("image_name");
// get resource id by image name
final int resourceId = resources.getIdentifier(imageName, "drawable", context.getPackageName());

hm.put("flag", Integer.toString(resourceId) );
aList.add(hm);
}

关于android - 本 map 片通过android中的本地json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23922964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com