ListView是android系統中比較常用的視圖組件,它的構建主要包含兩方面資訊:分別是UI組件的繪製和資料來源的設定。UI組件和資料來源之間通過適配器建立關聯。這裡的適配器充當媒人的角色,在為UI組件和資料來源介紹親事之前,媒人需要對雙方有所瞭解,瞭解的內容包括:ListItem的布局資訊和資料來源的實體資訊。
常用的適配器有兩種,分別是ArrayAdapter和SimpleAdapter
ArrayAdapter的應用情境:
ListItem顯示單一,只需顯示一條文本資訊即可
樣本圖:
針對這種顯示方式,android系統為我們提供了預設的ListItem布局
res\layout\simple_list_item_1.xml
[html]
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
android:paddingRight="?android:attr/listPreferredItemPaddingRight"
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
該布局定義了一個TextView用於顯示ListItem的常值內容,構造ArrayAdapter之前,只需將該TextView的id和布局檔案id作為參數傳遞至ArrayAdapter的構造參數中即可。
[java] view plaincopy
new ArrayAdapter<Word>(context,android.R.layout.simple_list_item_1,android.R.id.text1,List<?> dataSource);
第四個參數表資料來源資訊,TextView要顯示的常值內容即為List集合中實體元素的toString()值。
如果我們想自訂ListItem布局以便ListView的顯示更加豐富,那麼我們經常會用到另外一種適配器SimpieAdapter。
SimpieAdapter的資料來源呈如下結構:List<Map<String,Object>>,List集合中不再是實體物件,而是一個Map,Map.Entry會和ListItem進行綁定,而Map的Value值會映射到ListItem的顯示內容中去。
假設,我們構造了如下ListItem布局:
[html]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/fileItem_image"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_margin="4dp"
android:contentDescription="@string/img_desc"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/fileItem_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/fileItem_path"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
又提供了如下資料來源資訊:
[java]
List<Map<String,Object>> fileList=new ArrayList<Map<String,Object>>();
Map<String,Object> fileInfo=new HashMap<String,Object>();
fileInfo.put("img",R.drawable.img);
fileInfo.put("name","fileName");
fileInfo.put("path","filePath");
fileList.add(fileInfo);
便可通過如下構造器構建SimpleAdapter對象
[java]
new SimpleAdapter(context, fileList, R.layout.filelist_item, new String[]{"img", "name", "path"},
new int[]{R.id.fileItem_image, R.id.fileItem_name, R.id.fileItem_path});
由構造器可以看出,img、name和path分別和fileItem_image、fileItem_name和fileItem_path三個組件形成映射,它們的value值將會顯示到3個組件的常值內容中去。
顯示效果:
ListView組件可監聽如下事件:
選擇:setOnItemSelectedListener
單擊:setOnItemClickListener
長點擊事件:setOnItemLongClickListener
長點擊顯示contextMenu:setOnCreateContextMenuListener