在Android中,ListView是用來顯示一個列表的控件。每一行列表都是一個獨立的元素。這種控件既可以方便的顯示從系統中其他應用讀取出來的數據,也可獨立的爲各行元素設置監聽器。
根據API文檔中的說明,使用ListView顯示控件的基本流程如下:
1. 將所要顯示的數據以ArrayList,Cursor或者Array形式封裝成爲對象。
eg1:
|
eg2.
|
Cursor一般用於讀取其他應用程序的制定的數據。讀取完畢後,Cursor指向所得結果集的第一項數據。
|
2. 將所得到的數據加入到各自類型對應的適配器中。
2.1 ArrayList型
使用SimpleAdapter作爲適配器
public ArrayAdapter (Context context, int resource, int textViewResourceId)
Constructor
Parameters
context | The current context. |
---|---|
resource | The resource ID for a layout file containing a layout to use when instantiating views. |
textViewResourceId | The id of the TextView within the layout resource to be populated |
eg.
|
2.2 ContentProvider型
使用SimpleCursorAdapter作爲適配器
public SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)
Constructor.
Parameters
context | The context where the ListView associated with this SimpleListItemFactory is running |
---|---|
layout | resource identifier of a layout file that defines the views for this list item. The layout file should include at least those named views defined in "to" |
c | The database cursor. Can be null if the cursor is not available yet. |
from | A list of column names representing the data to bind to the UI. Can be null if the cursor is not available yet. |
to | The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter. Can be null if the cursor is not available yet. |
eg.
2.3 數組型
使用ArrayAdapter
public ArrayAdapter (Context context, int resource, int textViewResourceId)
Constructor
Parameters
context | The current context. |
---|---|
resource | The resource ID for a layout file containing a layout to use when instantiating views. |
textViewResourceId |
The id of the TextView within the layout resource to be populated
|