【问题标题】:Android: Dealing HashMap.put for imageAndroid:处理图像的 HashMap.put
【发布时间】:2012-02-18 08:16:20
【问题描述】:

我想在列表视图中添加图像,我该怎么做?名称和类型显示正确。目前卡在这里。

.//other codes
.
.
try{
        JSONArray arr = new JSONArray(res);
        for(int i=0;i<arr.length();i++){                        
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject e = arr.getJSONObject(i);

            map.put("placeID", ""+ e.getString("placeID"));
            map.put("placeName",""+ e.getString("placeName"));
            map.put("placeType", ""+ e.getString("placeType"));
            map.put("image", R.drawable.ball_green);

            mylist.add(map);            
        }       
    }catch(JSONException e)        {
         Log.e("log_tag", "Error parsing data "+e.toString());
    }

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.places, 
                    new String[] { "placeName", "placeType" }, 
                    new int[] { R.id.placeName, R.id.placeType });
.
.
.//other codes

我想要适当的图像:

【问题讨论】:

    标签: android image listview simpleadapter


    【解决方案1】:

    R.java 类在构建时自动生成,并维护一个整数“列表”,这些整数是资源 ID。换句话说,R.&lt;anything&gt; 是一个Integer,并不直接代表资源(字符串、可绘制等)。

    由于您的 HashMap 需要 String 类型的键和值,您需要将 ball_green 资源 ID 转换为 String。示例...

    map.put("image", String.valueOf(R.drawable.ball_green));
    

    为了再次使用它,您必须将 String 转换回 Integer,以便在使用它来设置诸如 ImageView 等小部件的图像时。

    【讨论】:

    • 我想知道,如果我下载了位图,如何在 map.put("image", String.valueOf(bitmapfile)); 中使用它有没有办法在这里连接下载的文件?
    • @Joe :如果您正在下载文件(位图或任何其他类型),它将永远不会在 R.java 类中分配一个 int 值,因此您不必使用 @987654332 @。 OP 使用的是HashMap&lt;String, String&gt; - 如果你也这样做,那么只需使用下载文件的路径作为第二个字符串。
    • 我会试试看!感谢回复
    【解决方案2】:

    我不认为将图像添加到哈希表中是一个好主意。您可以轻松添加自定义适配器,不要使用 SimpleAdapter。

    【讨论】:

      猜你喜欢
      • 2011-01-03
      • 1970-01-01
      • 2015-01-12
      • 2013-02-08
      • 2017-12-20
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多