【问题标题】:android listview with item and sub item not working properly带有项目和子项目的android listview无法正常工作
【发布时间】:2013-04-18 17:42:45
【问题描述】:

我有一个数据库,我选择 2 个字符串,一个作为项目,另一个是描述。我正在尝试将这 2 个字符串映射到列表视图项目子项目布局中。以下代码是我到目前为止所尝试的。

List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> datum = new HashMap<String, String>(2);
SimpleAdapter adapter = new SimpleAdapter(this, data,
        android.R.layout.simple_list_item_2, 
        new String[] { "item","descr" }, 
        new int[] { android.R.id.text1, android.R.id.text2 });
itemList.setAdapter(adapter);

Cursor cours = MainActivity.mydb.query("sub_menu", null, "cat_id = "
        + menuid + " AND sub_flag = 1", null, null, null, null);

if (cours.moveToFirst()) {
    do {
        datum.put("item", cours.getString(cours.getColumnIndex("sub_label")));
        datum.put("descr", cours.getString(cours.getColumnIndex("sub_description")));
        data.add(datum);
        Log.d("testt", datum.toString());

        adapter.notifyDataSetChanged();

    } while (cours.moveToNext());
}

现在的问题是,它将向列表视图添加 5 个条目,这些条目具有相同的值,这些条目是从数据库中选择的最后一行,这不是什么。知道如何解决这个问题吗?

编辑。 在尝试了它之后,我发现我正在覆盖最终具有所有条目的保存值的对象数据。修复就像将基准线的初始化线移动到循环中一样简单。这是最终代码

List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        String[] from = new String[] { "rowid", "col_1" };
        int[] to = new int[] { android.R.id.text1, android.R.id.text2 };

        Cursor cours = MainActivity.mydb.query("sub_menu", null, "cat_id = "
                + menuid + " AND sub_flag = 1", null, null, null, null);

        if (cours.moveToFirst()) {

            do {
                Map<String, String> datum = new HashMap<String, String>(2);
                datum.put("rowid",
                        cours.getString(cours.getColumnIndex("sub_label")));
                datum.put("col_1", cours.getString(cours
                        .getColumnIndex("sub_description")));
                data.add(datum);
            } while (cours.moveToNext());

        }
        SimpleAdapter adapter = new SimpleAdapter(this, data,
                android.R.layout.simple_list_item_2, from, to);
        itemList.setAdapter(adapter);

【问题讨论】:

  • 不要为while循环中的每次迭代调用adapter.notifyDataSetChanged();,在循环外调用它
  • 其实我没有理解你的问题,但是当我第一次看到adapter.notifyDataSetChanged(); 时,我只是发布了那个。在循环和如果条件之外调用它..我会尽力帮助你..如果你能澄清我
  • 我在数据库中有项目,例如 x,x1 y,y1 其中 x 和 y 是我想在我的列表视图中显示为项目 1 的字符串,而 item2 和 x1 和 y1 作为我想要的字符串在我的列表视图中显示为 subitem1 和 subitem2
  • 您需要制作自定义列表视图,才能做到这一点..

标签: android android-listview hashmap android-ui simpleadapter


【解决方案1】:

自定义 ListView 并使用 CursorAdapter Here 是一个很好的例子,可以帮助你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多