简体   繁体   English

如何使用哈希图设置图像

[英]How to set an image using a hash map

I want to set an image to a list view using a hash map, currently all data except the image is being set. 我想使用哈希图将图像设置为列表视图,目前正在设置除图像之外的所有数据。 How do i set the image using the hash map? 如何使用哈希图设置图像? The images are stored in the drawable folder. 图像存储在可绘制文件夹中。 Below is my code. 下面是我的代码。

    // create a List of Map<String, ?> objects
    ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

    for (Attraction attraction : attractions) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put(attraction_name, attraction.getName());
        map.put("img", String.valueOf(R.drawable.king));
        data.add(map);
    }

    // create the resource, from, and to variables
    int resource = R.layout.layout_att;

    String[] from = {attraction_name, "img"};
    int[] to = {R.id.name, R.id.img};

    // create and set the adapter
    SimpleAdapter adapter =
            new SimpleAdapter(this, data, resource, from, to);

    attractionListListView.setAdapter(adapter);

    attractionListListView.setOnItemClickListener(this);

}

You can use: http://developer.android.com/reference/android/widget/ImageView.html#setImageResource(int) 您可以使用: http : //developer.android.com/reference/android/widget/ImageView.html#setImageResource(int)

in your adapter, do something like: 在您的适配器中,执行以下操作:

imageView.setImageResource((int) hashMap.get("img"));

although, I'd really recommend you to have a class instead of a hash map to do such a thing. 但是,我确实建议您使用一个类而不是哈希映射来执行此操作。 This way you would have a List of your class (it could be even a inner class just to help you organize) instead of a hash map. 这样,您将拥有一个类列表(它甚至可以是一个内部类,只是为了帮助您进行组织),而不是哈希映射。 With this you would avoid casting the hashmap content to int. 这样,您就可以避免将哈希映射内容强制转换为int。

But other then that if you really want to use the hashmap, you can use the code I've written above. 但是除此之外,如果您真的想使用哈希图,则可以使用我上面编写的代码。

Regards 问候

I don't think that you need to keep binary data (stream) in Map, it can be good if you read it when needed. 我认为您不需要将二进制数据(流)保留在Map中,如果您在需要时读取它,可能会很好。 You can not handle binary image as String.. 您不能将二进制图像作为String处理。

See this thread for a solution: How to display a list of images in a ListView in Android? 查看此线程以获取解决方案: 如何在Android的ListView中显示图像列表?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM