【问题标题】:How to display Images in ListView android如何在 ListView android 中显示图像
【发布时间】:2026-01-15 06:25:02
【问题描述】:

我一直在寻找有关如何执行此操作的示例。在 * 上发现了一种使用 SimpleAdapter 和 HashMaps 的方法。 这是我的代码。它不工作。我只能看到一个列表的空行。

listItems = new ArrayList<HashMap<String,Object>>();

HashMap<String,Object> listData1 = new HashMap<String,Object>();
HashMap<String,Object> listData2 = new HashMap<String,Object>();

image_1 = getResources().getDrawable(R.drawable.camera_icon_focus_dim);
image_2 = getResources().getDrawable(R.drawable.camera_icon_scene_mode);

listData1.put("icon focus", image_1);
listData2.put("icon_scene", image_2);

listItems.add(listData1);
listItems.add(listData2);

SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItems,
  R.layout.image_list_item, new String[]{"icon_focus"}, 
  new int[]{R.id.list_view_item1});

optionsList.setAdapter(listItemAdapter);

image_list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<ImageView   xmlns:android="http://schemas.android.com/apk/res/android"
        android:paddingTop="12dip"       
        android:layout_width="wrap_content"       
        android:layout_height="wrap_content"        
        android:id="@+id/listitem_img"
    />

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_view_item1"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1.0"
/>

请告诉我我做错了什么。

【问题讨论】:

标签: android listview imageview hashmap simpleadapter


【解决方案1】:

HashMap 中的字段需要匹配。试试这个:

listItems = new ArrayList<HashMap<String,Integer>>();
String fieldName = "icon_id";

HashMap<String, Integer> listData1 = new HashMap<String, Integer>();
HashMap<String, Integer> listData2 = new HashMap<String, Integer>();

listData1.put(fieldName, R.drawable.camera_icon_focus_dim);
listData2.put(fieldName, R.drawable.camera_icon_scene_mode);

listItems.add(listData1);
listItems.add(listData2);

SimpleAdapter listItemAdapter = new SimpleAdapter(
    this,
    listItems,
    R.layout.image_list_item,
    new String[] { fieldName },
    new int[] { R.id.listitem_img });

【讨论】:

  • 成功了!谢谢 :) 但是,我不明白为什么。你能解释一下吗?
  • 有两个并行数组传递给SimpleAdapter,一个带有String,一个带有int。每个位置将HashMap 中的键映射到模板中指定的View(在您的情况下为R.layout.image_list_item)。 ListView 从列表中获取一个项目,即HashMap,使用键(示例中为"icon_id")获取填充View(示例中为R.id.listitem_img)的值。您可以在列表项模板中显示多个字段,方法是使用不同的键存储它,将该键附加到 String[] 并将相应的视图 ID 附加到 int[]
  • 为什么文本没有添加到列表视图中? @chiuki
最近更新 更多