一个ListView显示出来需要3个东西: 1,listview(用来显示数据的列表)。 2,Data(需要显示的数据)。 3,一个绑定Data和Listview的适配器ListAdapter。 一,ListView 1,ListView的每一项其实都是TextView。 2,通过setAdapter方法来调用一个listAdapter来绑定数据。 二,ListAdapter 1,ListAdapter是绑定Data和Listview的适配器。但是,它是接口,需要使用它的子类。 常见的子类有:arrayAdapter,SimpleAdapter ,CursorAdapter 2,android系统默认提供了很多默认的布局方式,也可以自定义。 Android.R.layout.simple_list_item_1:每一项只有一个TextView Android.R.layout.simple_list_item_2:每一项有两个TextView Android.R.layout.simpte.list_item_single_choice,每一项有一个TextView,但是这一项可以被选中。 三,ArrayAdapter 1,数组适配器,它的作用就是一个数组和listview之间的桥梁,它可以将数组里边定义的数据一一对应的显示在Listview里边。 2,ListView的每个TextView里边显示的内容就是数组里边的对象调用toString()方法后生成的字符串。 3,这是一个简单创建一个list的例子其中的代码: ListView listview=new ListView(this); // 构造一个listview对象 String[] data = {“google”,”amazon”,”facebook”}; // 构造一个数组对象,也就是数据 listview.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_single_choice, data)); //构造一个array适配器,然后listview对象通过setAdapter方法调用适配器来和自己绑定数据 list.setItemsCanFocus(true); list.setChoiceMode(listview.CHOICE_MODE_MULTIPLE); setContentView(listview); 四,SimpleAdapter 1,作用是ArrayList和ListView的桥梁。这个ArrayList里边的每一项都是一个Map<String,?>类型。ArrayList当中的每一项Map对象都和ListView里边的每一项进行数据绑定一一对应。 2,SimpleAdapter的构造函数: SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) 参数: 1,context:上下文。 2,data:基于Map的list。Data里边的每一项都和ListView里边的每一项对应。Data里边的每一项都是一个Map类型,这个Map类里边包含了ListView每一行需要的数据。 3,resource :就是一个布局layout,可引用系统提供的,也可以自定义。 4,from:这是个名字数组,每个名字是为了在ArrayList数组的每一个item索引Map<String,Object>的Object用的。 5,to:里面是一个TextView数组。这些TextView是以id的形式来表示的。例如:Android.R.id.text1,这个text1在layout当中是可以索引的。 3,通过一个类子来理解下: listitem.xml文件: <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas./apk/res/android” android:orientation=”horizontal” android:layout_width=”fill_parent” android:layout_height=”wrap_content”> <TextView android:id=”@+id/mview1″ android:layout_width=”100px” android:layout_height=”wrap_content” /> <TextView android:id=”@+id/mview2″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” /> </LinearLayout> 下面是activity文件的部分代码 List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); Map<String,Object> item; item = new HashMap<String,Object>(); item.put(“姓名”,”张三”); item.put(“性别”,”男”); data.add(item); item = new HashMap<String,Object>(); item.put(“姓名”,”李四”); item.put(“性别”,”女”); data.add(item); // 上面是构造数据部分。 ListView listview= new ListView(this); //构造listview对象。 SimpleAdapter adapter = new SimpleAdapter(this,data,R.layout.listitem,new String[]{“姓名”,”性别”},new int[]{R.id.TextView01,R.id.TextView02}); /*构造一个适配器。 * 1,第三个参数是说明用的是自定义的布局R.layout.listtiem。 * 2,第四和第五个参数一起理解: * 把我们添加数据时姓名那一列对应到R.id.TextView01这个TextView中,把性别对应到R.id.TextView02这个TextView中。 * 如果把from改为new String[]{“姓名”,”姓名”},测试下就会明白。 */ listview.setAdapter(adapter); setContentView(listview); |
|