Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實作:長按 ListView 顯示 CheckBox 並批量刪除

編輯:關於 Android 程式設計

可編輯、可刪除的列表,如果不能批量操作,使用者得逐項刪除,體驗非常糟糕。本文示範如何透過長按喚出多選模式,完成批量刪除。

一、主版面配置(select.xml)

版面包含一個 ListView,以及一個預設隱藏的操作列——裡頭有兩個按鈕與一個文字提示,偵測到長按事件時才顯示。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:cacheColorHint="#FFF" />

    <RelativeLayout
        android:id="@+id/relative"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:gravity="bottom"
        android:background="@color/lemonchiffon"
        android:visibility="gone" >

        <Button
            android:id="@+id/cancle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="撤銷"
            android:textSize="20sp"
            android:background="@null"
            android:layout_centerVertical="true" />

        <TextView
            android:id="@+id/txtcount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="共計"
            android:textSize="15sp"
            android:layout_centerInParent="true" />

        <Button
            android:id="@+id/delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="刪除"
            android:textSize="20sp"
            android:background="@null"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true" />

    </RelativeLayout>
</LinearLayout>

二、單項配置(item.xml)

一個 TextView 加一個 CheckBox,CheckBox 預設隱藏且不可點擊(點擊事件交給整列處理)。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/txtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="5dp"
        android:layout_weight="1"
        android:textSize="17sp"
        android:textColor="#333" />

    <CheckBox
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:clickable="false" />
</LinearLayout>

三、自訂 Adapter

用兩個 HashMap 分別記錄「CheckBox 是否顯示」與「是否被勾選」,再透過長按監聽切換狀態。長按監聽務必回傳 true,否則事件會被 ListView 吃掉。

class Adapter extends BaseAdapter {

    private Context context;
    private LayoutInflater inflater = null;
    private HashMap<Integer, View> mView;

    public HashMap<Integer, Integer> visiblecheck;   // 記錄是否顯示 CheckBox
    public HashMap<Integer, Boolean> ischeck;        // 記錄是否被勾選
    private TextView txtcount;

    public Adapter(Context context, TextView txtcount) {
        this.context = context;
        this.txtcount = txtcount;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mView = new HashMap<Integer, View>();
        visiblecheck = new HashMap<Integer, Integer>();
        ischeck = new HashMap<Integer, Boolean>();

        int visible = isMulChoice ? CheckBox.VISIBLE : CheckBox.INVISIBLE;
        for (int i = 0; i < array.size(); i++) {
            ischeck.put(i, false);
            visiblecheck.put(i, visible);
        }
    }

    @Override
    public int getCount() {
        return array.size();
    }

    @Override
    public Object getItem(int position) {
        return array.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = mView.get(position);
        if (view == null) {
            view = inflater.inflate(R.layout.item, null);
            TextView txt = (TextView) view.findViewById(R.id.txtName);
            final CheckBox ceb = (CheckBox) view.findViewById(R.id.check);

            txt.setText(array.get(position));
            ceb.setChecked(ischeck.get(position));
            ceb.setVisibility(visiblecheck.get(position));

            view.setOnLongClickListener(new Onlongclick());
            view.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (isMulChoice) {
                        if (ceb.isChecked()) {
                            ceb.setChecked(false);
                            selectid.remove(array.get(position));
                        } else {
                            ceb.setChecked(true);
                            selectid.add(array.get(position));
                        }
                        txtcount.setText("共選擇了" + selectid.size() + "項");
                    } else {
                        Toast.makeText(context, "點擊了" + array.get(position), Toast.LENGTH_LONG).show();
                    }
                }
            });

            mView.put(position, view);
        }
        return view;
    }

    class Onlongclick implements OnLongClickListener {
        public boolean onLongClick(View v) {
            isMulChoice = true;
            selectid.clear();
            layout.setVisibility(View.VISIBLE);
            for (int i = 0; i < array.size(); i++) {
                adapter.visiblecheck.put(i, CheckBox.VISIBLE);
            }
            adapter = new Adapter(context, txtcount);
            listview.setAdapter(adapter);
            return true;   // 一定要回傳 true
        }
    }
}

四、Activity 主體

package com.example.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MulSelect extends Activity implements OnClickListener {

    private ListView listview;
    private Context context;
    private List<String> array = new ArrayList<String>();
    private List<String> selectid = new ArrayList<String>();
    private boolean isMulChoice = false;    // 是否多選
    private Adapter adapter;
    private RelativeLayout layout;
    private Button cancle, delete;
    private TextView txtcount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select);
        context = this;

        listview = (ListView) findViewById(R.id.list);
        layout = (RelativeLayout) findViewById(R.id.relative);
        txtcount = (TextView) findViewById(R.id.txtcount);
        cancle = (Button) findViewById(R.id.cancle);
        delete = (Button) findViewById(R.id.delete);
        cancle.setOnClickListener(this);
        delete.setOnClickListener(this);

        init();
        adapter = new Adapter(context, txtcount);
        listview.setAdapter(adapter);
    }

    void init() {
        for (int i = 0; i < 20; i++) {
            array.add("小明" + i);
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancle:
                isMulChoice = false;
                selectid.clear();
                adapter = new Adapter(context, txtcount);
                listview.setAdapter(adapter);
                layout.setVisibility(View.INVISIBLE);
                break;

            case R.id.delete:
                isMulChoice = false;
                for (int i = 0; i < selectid.size(); i++) {
                    for (int j = 0; j < array.size(); j++) {
                        if (selectid.get(i).equals(array.get(j))) {
                            array.remove(j);
                            break;   // 找到即跳出,避免索引錯位
                        }
                    }
                }
                selectid.clear();
                adapter = new Adapter(context, txtcount);
                listview.setAdapter(adapter);
                layout.setVisibility(View.INVISIBLE);
                break;

            default:
                break;
        }
    }
}

五、這個實作可以更好的地方

用 position 當 key 是脆弱的。範例以 position 作為 HashMap 的索引,一旦資料集變動,所有記錄都會錯位。實務上應改用資料本身的穩定識別碼(例如 id 欄位)來記錄勾選狀態。

mView 快取會妨礙回收。把每個 View 都存進 HashMap 等於關掉了 ListView 的 view recycling 機制,長列表下會吃大量記憶體。範例這樣寫是為了簡化狀態同步,正式專案應改用 convertView 重用,並搭配 SparseBooleanArray 記錄勾選狀態。

重新 new Adapter 太耗資源。切換多選模式時不必重建整個 Adapter,只要呼叫 notifyDataSetChanged() 並同步可見性即可。

更好的替代方案。若 targetSdk 較高,可直接使用 ListView.setChoiceMode(CHOICE_MODE_MULTIPLE_MODAL) 搭配 MultiChoiceModeListener,系統會自動處理長按進入多選、Action Bar 顯示已選數量、返回鍵退出等細節,程式碼量能少一大半。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved