ListView 列表是我們經常會使用的控件, 如果想要自定義裡面的顯示的話是挺麻煩的, 需要新建XML、Class SimpleAdapter這兩個文件, 較為麻煩。 如果我們隻是想顯示兩、三行文字在上面, 卻又不想那麼麻煩呢? 那我們隻要新建一個XML就夠瞭。
這裡以顯示一個ListView項裡三個TextView為例。
首先我們要創建一個XML文件, 這個XML文件是用來作為單個ListView項佈局用的。
list_row.xml
[java]
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
>
<TextView
android:id="@+id/textTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dip"
android:textColor="#333333"
/>
<TextView
android:id="@+id/textOwn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textTo"
android:textSize="12dip"
android:textColor="#999999"
/>
<TextView
android:id="@+id/textState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:textSize="14dip"
android:textColor="#999999"
/>
</RelativeLayout>
第一個TextView是標題、第二個是內容、第三個是狀態
接下來我們需要在主XML佈局文件裡面放置一個ListView控件
[html]
<?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"
android:orientation="vertical"
android:background="#ffffff"
>
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
></ListView>
</LinearLayout>
然後,我們要在主Activity裡面聲明三個成員變量
[java]
private List<Map<String, Object>> mList;
private ListView mListView;
private SimpleAdapter mListAdapter;
mList是用來存放要顯示的數據
SimpleAdapter是ListView 數據的一個容器, 用來存放顯示在ListView上的數據。 對 SimpleAdapter 的數據操作會直接影響到ListView的顯示。
然後, 我們來給mList添加一些要顯示的數據
[java]
mList = new ArrayList<Map<String,Object>>();
[java]
Map<String, Object> map = new HashMap<String, Object>();
map.put("First", "這是標題");
map.put("Next", "這是內容");
map.put("State", "狀態");
mList.add(map);
這樣就添加瞭一條數據, 如果要添加多條就重復再添加。
接下來我們把數據放入到SimpleAdapter/ListView中
[java]
mListAdapter = null;
mListAdapter = new SimpleAdapter(this, mList, R.layout.list_row,
new String[]{"First", "Next", "State"},
new int[]{R.id.textOwn, R.id.textTo, R.id.textState});
mListView.setAdapter(mListAdapter);
new SimpleAdapter的參數: 父指針、ArrayList的數據、 佈局文件、 要顯示的數據的標簽、顯示在哪些控件上。 後面兩個參數順序一定要對應。
最後, ListView載入瞭SimpleAdapter就可以瞭。
當然,我們直接操作mList也會影響到ListView的數據。 在修改瞭mList的數據後,調用SimpleAdapter的notifyDataSetChanged()方法後就可以瞭。
摘自 KnowHeart-Kress