1

我有一个列表视图,它的数据值由块(Item1,Item2...)分隔,但我想知道如何显示(Item 1,Sub Item 1...)?那么这里是只显示项目的代码,那么我如何显示项目和子项目呢?

代码:

           //LISTVIEW database CONTATO
    ListView user = (ListView) findViewById(R.id.lvShowContatos);
    //String = simple value ||| String[] = multiple values/columns
    String[] campos = new String[] {"nome", "telefone"};

    list = new ArrayList<String>();
    Cursor c = db.query( "contatos", campos, null, null, null, null, "nome" + " ASC ");
    c.moveToFirst();
    String lista = "";
    if(c.getCount() > 0) {
        while(true) {
           list.add(c.getString(c.getColumnIndex("nome")).toString());
            if(!c.moveToNext()) break;
        }
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, list);

    user.setAdapter(adapter);

我放在那里的代码但仍然给我错误,我还没有看到它从哪里获取值。

             //LISTVIEW database CONTATO
    ListView user = (ListView) findViewById(R.id.lvShowContatos);
    //String = simple value ||| String[] = multiple values/columns
    String[] campos = new String[] {"nome", "telefone"};


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

    Cursor c = db.query( "contatos", campos, null, null, null, null, "nome" + " ASC ");
    c.moveToFirst();

    listItem = new HashMap<String, Object>();
    listItem.put("nome", "your_item_text");
    listItem.put("telefone", "your_subitem_text");
    items.add(listItem);

    adapter = new SimpleAdapter(this, items, R.layout.custom_list_layout, new String[]{"item", "subitem"}, new int[]{R.id.text_item, R.id.text_subitem});

    user.setAdapter(adapter);
4

3 回答 3

1

使用SimpleAdapter,而不是ArrayAdapter填充ListView: http: //developer.android.com/reference/android/widget/SimpleAdapter.html 在那里,您将有一个字段数组来填充每个项目,例如:

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

listItem = new HashMap<String, Object>();
listItem.put("item", "your_item_text");
listItem.put("subitem", "your_subitem_text");
items.add(listItem);

adapter = new SimpleAdapter(this, items, R.layout.custom_list_layout, new String[]{"item", "subitem"}, new int[]{R.id.text_item, R.id.text_subitem});

listview.setAdapter(adapter);

还要记住custom_list_layout.xml为您的 ListView 项目创建,并确保它包含具有正确 id 的 textView:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/text_item"
        ... />

    <TextView
        android:id="@+id/text_subitem"
        ... />

</RelativeLayout>
于 2012-09-14T19:44:49.713 回答
0

查看ExpandableListView,这正是这个用户案例。

于 2012-09-14T19:23:03.353 回答
0

您必须创建自己的自定义适配器来扩展 ArrayAdapter 或 BaseAdapter,并且还必须为列表中的项目创建 xml 布局。
如果您是 ListView 的新手,请阅读有关 ListView 的本教程

于 2012-09-14T19:42:57.387 回答