Android下的ListView一般应用指南

一,显示:
ListView的Layout需要两个xml。第一个xml,在其中添加ListView本身,把ListView添加到需要显示的位置;第二个xml,则是定义ListView需要显示的内容的Layout。

定义ListView内容的Layout和一般的Layout一样,除了一些限制,比如不要在里面添加EditText之类带输入焦点的View。

info_list.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent">
    <TextView
        android:layout_height="wrap_content"
        android:id="@+id/txtName" android:layout_width="fill_parent" android:layout_weight="0.7" android:text="name" android:layout_marginRight="1px" android:background="#c0ffffb0" android:textColor="#000000"></TextView>
    <TextView
        android:layout_height="wrap_content"
        android:id="@+id/txtExp"
    android:layout_width="fill_parent" android:layout_weight="0.3" android:text="expression" android:background="#c0ffb600" android:textColor="#000000"></TextView>
</LinearLayout>

把ListView内容的Layout和ListView绑定在一起就可以显示了。一般的应用,使用SimpleAdapter就可以了:

SimpleAdapter listItemAdapter = new SimpleAdapter(this,
listItem,
R.layout.inf_list,
new String[] {"lstItmDate", "lstItmWeek"},
new int[] {R.id.txtvwWeek,R.id.txtvwWeekInfo});

SimpleAdapter的构造需要使用到一个List (listItem),使用如下的定义可以创建一个List:

ArrayList> listItem = new ArrayList>();

ArrayList需要使用到hashmap:

HashMap mapBase = new HashMap();

HashMap用来存储一对数值,比如:

mapBase.put("lstItmDate", "2010 04 26");
mapBase.put("lstItmWeek", "Monday");

可以很明显的看出来,HashMap中的”lstItmDate”和”lstItmWeek”与SimpleAdapter中的对应。

把HashMap添加到ArrayList中,显示部分就完成了:

listItem.add(mapBase);

所以,作为总结,一个ListView需要涉及如下几个部分:

  1. HashMap
  2. ArrayList
  3. SimpleAdapter
  4. ListView