Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 小專案:ListView 實作論壇列表,含 CheckBox 與長按選單

編輯:Android 開發實例

在 Android 裡,ListView 幾乎是所有列表畫面的起點。要讓它顯示資料,中間必須墊一層 Adapter;常見選擇有 ArrayAdapter 與 SimpleAdapter。網路上不少範例會直接繼承 ListActivity,本例刻意繼承普通的 Activity,把 ListView 當成一般元件來操作,這樣做的好處是版面自由度更高,也更容易理解底層流程。

本篇的目標清單

  1. 準備 ListView 要顯示的資料,以一維或多維動態陣列保存;
  2. 建立 Adapter,動態陣列有幾筆就產生幾列;
  3. 把 Adapter 掛到 ListView 並顯示;
  4. 每一列帶一個 CheckBox,同時保留單擊與長按事件,單擊時弹出該列內容;
  5. 長按後弹出 Menu 對話框,可執行「高亮」與「置頂」等操作。

版面:主畫面與列樣式

主版面很單純,一個 LinearLayout 包一個 ListView:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ListView
        android:id="@+id/ListView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

列的樣式則用 RelativeLayout 疊出「標題在上、說明在下、勾選框靠右」的結構:

<RelativeLayout android:id="@+id/RelativeLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="4dip"
    android:paddingLeft="12dip"
    android:paddingRight="12dip"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <CheckBox
        android:id="@+id/CheckBox01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:paddingTop="12dip"
        android:focusable="false" />

    <TextView
        android:id="@+id/topTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20dip" />

    <TextView
        android:id="@+id/bottomTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/topTextView" />
</RelativeLayout>

關鍵陷阱:CheckBox 會搶走整列的點擊

這是新手最常撞到的牆。CheckBox 在 Android 中的焦點優先級高於 ListView 列本身,畫面一載入,焦點就會預設落在第一列的 CheckBox 上,導致點擊列的其他區域沒有反應。解法是在 CheckBox 上加上:

android:focusable="false"

若還有子元件互搶焦點,可以視情況搭配 android:focusableInTouchMode="false",或在列的根版面設 android:descendantFocusability="blocksDescendants",讓整列的事件統一由 ListView 處理。

Java 端:資料、Adapter、事件

public class testListViewActivity extends Activity {

    private ListView myListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myListView = (ListView) findViewById(R.id.ListView01);

        ArrayList<HashMap<String, Object>> listitem = new ArrayList<HashMap<String, Object>>();
        for (int i = 1; i <= 10; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("ItemTitle", "文章 " + i);
            map.put("ItemText", "Android 小專案 " + i);
            listitem.add(map);
        }

        SimpleAdapter adapter = new SimpleAdapter(
                this,
                listitem,
                R.layout.listview_style,
                new String[]{"ItemTitle", "ItemText"},
                new int[]{R.id.topTextView, R.id.bottomTextView});
        myListView.setAdapter(adapter);
        // ...事件設定見下文
    }
}

這裡用 ArrayList<HashMap<String, Object>> 而非單純字串陣列,理由是後續要靠 key 去對應各子檢視,資料結構的彈性換來版面的彈性。注意這個集合必須 new 出來,不可留空。

接著看 SimpleAdapter 的五個參數,理解它的「從哪裡來、到哪裡去」:

  1. context:上下文,一般傳 this;
  2. data:資料源,也就是剛才那個 listitem;
  3. resource:列的版面檔,如 R.layout.listview_style;
  4. from:要取出哪些 key,如 {"ItemTitle", "ItemText"};
  5. to:要塞進哪些檢視的 id,順序必須與 from 一一對應。

單擊:用 getChildAt 取出列內元件

單擊時,回呼的 View 參數就是「被點的那一列」的跟節點。只要把它轉型成 RelativeLayout,再用 getChildAt() 依索引取出子檢視即可。

myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView mText = (TextView) view.findViewById(R.id.topTextView);
        Toast.makeText(testListViewActivity.this,
                "你點擊了第 " + position + " 項:" + mText.getText().toString(),
                Toast.LENGTH_SHORT).show();
    }
});

這裡示範用 findViewById 取代硬寫的 getChildAt(1)。兩者效果相同,但 id 定位不受版面巢狀層數影響,日後改版面也不易出錯。若堅持用索引,務必確認列結構沒有變動。

長按:弹出上下文選單

myListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        TextView title = (TextView) ((View) info.targetView).findViewById(R.id.topTextView);
        menu.setHeaderIcon(R.drawable.icon);
        menu.setHeaderTitle(title.getText());
        menu.add(0, 0, 0, "高亮");
        menu.add(0, 1, 1, "置頂");
    }
});

選單被點選後,事件會回到 Activity 的 onContextItemSelected(),用 item.getItemId() 分辨是哪一項,再對 info.position 指到的列做處理:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info =
            (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    TextView title = (TextView) info.targetView.findViewById(R.id.topTextView);
    switch (item.getItemId()) {
        case 0:
            title.setBackgroundColor(Color.BLUE);
            return true;
        case 1:
            Toast.makeText(this, title.getText() + " 已置頂", Toast.LENGTH_SHORT).show();
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

原作者示範的是先抓 getChildAt(0) 拿到 ListView 再往下挖,那樣寫法在「長按後要正確指向被按的列」這件事上會失準,因為 getChildAt(0) 永遠是第一個可見列。AdapterContextMenuInfo 才是框架為此準備的答案。

還剩下的功課

  • 要在 ListView 裡做圖片的動態切換,需要更細緻的刷新策略,可考慮 ViewHolder 搭配 notifyDataSetChanged(),避免整列重繪。
  • 資料量大時應改用 BaseAdapter 並實作 convertView 重用,SimpleAdapter 只適合結構單純的清單。
  • 宣告 ArrayList<HashMap<String, Object>> 時務必 new 出來,否則一取值就是空指針。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved