ListView中最主要的是adapter的设置问题,这里简单写了两个Adapter。
第一种ArrayAdapter:
private static String[] data1={"a","b","c","d"};
private List data2=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView listview=new ListView(this);
ArrayAdapter adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,data);
setContentView(listview);
其中样式 每条数据样式可自己定义,或使用系统自带的样式,如android.R.layout.simple_list_item_1。
如一行有多条数据,采用第二种SimpleAdapter:
先将数据放到 ArrayList<Map<String,Object>>中去,每条记录都是一个Map映射列表。
data2=new ArrayList<Map<String,Object>>();
Map<String, Object> item;
item=new HashMap<String,Object>();
item.put("姓名","张三");
item.put("性别","男");
data2.add(item);
item=new HashMap<String,Object>();
item.put("姓名","李四");
item.put("性别","男");
data2.add(item);
item=new HashMap<String,Object>();
item.put("姓名","小王");
item.put("性别","女");
data2.add(item);
SimpleAdapter adapter=new SimpleAdapter(this, data2, R.layout.listitem, new String[]{"姓名", "性别"},new int[]{R.id.mview1,R.id.mview2});
listview.setAdapter(adapter);
setContentView(listview);
SimpleAdapter的构造函数最后两个参数,一个是String数组,里面每个字符串用于访问得到Map对象中的值。item.get("姓名");最后一个参数数组里的值为xml中两个TextView的ID。
其中list选项的样式可自己定义
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/mview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:width="300dp"> </TextView> <TextView android:id="@+id/mview2" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> </LinearLayout>