如何在Android中向列表视图项添加图片?

3

我正在尝试为我的每个列表项添加不同的图标,但遇到了问题。我的想法是将每个列表视图项目放在一起以便更容易进行编辑,但添加图像比我想象的要复杂。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ArrayList<Map<String, String>> list = buildData();
    String[] from = { "title", "description" };
    int[] to = { android.R.id.text1, android.R.id.text2 };

    SimpleAdapter adapter = new SimpleAdapter(this, list,
            android.R.layout.simple_list_item_2, from, to);
    setListAdapter(adapter);
}

private ArrayList<Map<String, String>> buildData() {
    ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
    list.add(putData("Title 1", "Description 1"));
    list.add(putData("Title 2", "Description 2"));
    list.add(putData("Title 3", "Description 3"));
    return list;
}

private HashMap<String, String> putData(String name, String purpose) {
    HashMap<String, String> item = new HashMap<String, String>();
    item.put("name", name);
    item.put("purpose", purpose);
    return item;
}
3个回答

1
这在你现有的设置下,要么不可能,要么非常麻烦。
顾名思义,“SimpleAdapter”是一个提供基本功能的基础类。一般来说,它会提供一个带文本视图的列表。
当你创建适配器时,你为其中的每个单独项目指定了一个精确的布局(即android.R.layout_simple_list_item_2)。你无法添加任何其他项目(除非你真的很固执)。
你需要的是:
  • 自定义适配器(最好)
  • 自定义适配器布局
  • 适配器中的数据源将为每个元素映射特定的图标。
这是一个不错的演示:http://hmkcode.com/android-custom-listview-titles-icons-counter/

谢谢,看起来就是我想要的。 - mattFllr

0

你可以在ListView中使用自定义适配器,以便自定义每一行的样式。请查看this


0

目前使用 simple_list_item_2.xml 作为 ListView 的布局。该布局仅包含两个 TextView。因此,无法在 ListView 行中使用 simple_list_item_2.xml 布局显示图像。

如何在 Android 中向列表视图项添加图像?

应创建自定义适配器:

1. 创建具有所需视图的自定义布局,例如 TextView、ImageView 等,以在每个 ListView 行中显示

2. 创建自定义适配器类,通过扩展 SimpleAdapter 类来更改 getView 方法的行为,以从数据源中显示图像和文本视图

请参考以下教程:

在 Android 中使用 Simple Adapter 显示带有图像和文本的 ListView


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接