我有一个listview,它的数据值由块(Item1,Item2 ...)分隔,但我想知道如何显示(Item 1,Sub Item 1 ...)? 以下是仅显示Item的代码,那么如何显示Item和Sub Item?
代码:
//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);
答案 0 :(得分: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);
还要记住为ListView项创建custom_list_layout.xml
,并确保它包含带有正确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>
答案 1 :(得分:0)
查看ExpandableListView,这正是针对此用户案例。
答案 2 :(得分:0)
您必须创建自己的自定义适配器,扩展ArrayAdapter或BaseAdapter,您还必须为列表中的项目创建xml布局。
如果您不熟悉ListView,请在ListView上查看此tutorial。