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

Android 實現用戶列表的滑動刪除與多選批量刪除

編輯:關於 Android 程式設計

列表數據的刪除是極常見的需求。Android 上主流有兩種交互模式:一種類似微信,向左滑動露出刪除按鈕;另一種是通過 CheckBox 勾選多項,再點擊底部按鈕批量刪除。本文把這兩種方式整合進同一個列表。

設計思路

核心邏輯全部集中在適配器 MyAdapter 中,需要三樣狀態:

  • 一個 Map,記錄每一項的刪除按鈕應該顯示還隱藏;
  • 一個 Map,記錄每一項的 CheckBox 是否被勾選;
  • 一個與 Activity 通信的接口 ContentsDeleteListener,含兩個方法:contentsDeleteSelect(position, isChecked) 負責同步勾選集合,contentDelete(position) 負責刪除指定項。

滑動效果的判定很簡單:當手指橫向位移超過 40 像素時,顯示該項的刪除按鈕;同時把其他所有項的刪除按鈕隱藏、CheckBox 復位,保證任何時刻只有一項處於「展開」狀態。

一、主界面布局

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/my_delete_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="@string/delete" />

    <ListView
        android:id="@+id/my_lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_above="@id/my_delete_btn" />

</RelativeLayout>

結構很單純:底部一個批量刪除按鈕,上方一個 ListView。

二、單項布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/my_rl"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <CheckBox
        android:id="@+id/my_select_cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:background="@drawable/my_list_checkbox_selector"
        android:button="@null" />

    <TextView
        android:id="@+id/my_content_tv"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_centerInParent="true"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@id/my_select_cb"
        android:gravity="center"
        android:text="@string/delete" />

    <TextView
        android:id="@+id/my_delete_tv"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerInParent="true"
        android:layout_marginLeft="5dp"
        android:clickable="true"
        android:drawableLeft="@drawable/del_icon_normal"
        android:gravity="center"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="@string/delete"
        android:visibility="gone" />

</RelativeLayout>

注意 CheckBox 用了 android:button="@null" 搭配自定義 background,這樣才能完全控制勾選態的外觀;刪除 TextView 預設 visibility="gone",由適配器控制顯隱。

三、CheckBox 選擇器

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/my_list_check_box_bg_check"
          android:state_checked="true" />
    <item android:drawable="@drawable/my_list_check_box_bg_check"
          android:state_selected="true" />
    <item android:drawable="@drawable/my_list_check_box_bg_check"
          android:state_pressed="true" />
    <item android:drawable="@drawable/my_list__check_box_bg" />
</selector>

四、適配器 MyAdapter

package com.example.slideandselectdeletedemo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

@SuppressLint("UseSparseArrays")
public class MyAdapter extends BaseAdapter {

    private LayoutInflater mInflater;
    private List<String> mContentsList;
    private Context mContext;
    private ContentsDeleteListener mContentsDeleteListener;

    /** 記錄每一項刪除按鈕的顯示狀態 */
    private Map<Integer, Integer> visibleDeleteTv;
    /** 記錄每一項 CheckBox 的勾選狀態 */
    private Map<Integer, Boolean> selectCb;
    /** 滑動時的上一個 X 坐標 */
    private int mLastX = 0;

    public MyAdapter(Context mContext, List<String> mContentsList,
                     ContentsDeleteListener listener) {
        this.mContext = mContext;
        this.mContentsList = mContentsList;
        this.mContentsDeleteListener = listener;
        this.mInflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        visibleDeleteTv = new HashMap<Integer, Integer>();
        selectCb = new HashMap<Integer, Boolean>();

        // 初始狀態:全部未勾選、刪除按鈕隱藏
        for (int i = 0; i < mContentsList.size(); i++) {
            visibleDeleteTv.put(i, View.GONE);
            selectCb.put(i, false);
        }
    }

    public void updateView(List<String> list) {
        this.mContentsList = list;
        notifyDataSetChanged();
    }

    @Override public int getCount() { return mContentsList.size(); }
    @Override public Object getItem(int position) { return mContentsList.get(position); }
    @Override public long getItemId(int position) { return position; }

    @Override
    public View getView(final int position, View convertView,
                        ViewGroup parent) {
        final HolderView holderView;
        if (convertView == null) {
            holderView = new HolderView();
            convertView = mInflater.inflate(
                    R.layout.activity_main_list_view, null);
            holderView.listSelectCb =
                    (CheckBox) convertView.findViewById(R.id.my_select_cb);
            holderView.listContentTv =
                    (TextView) convertView.findViewById(R.id.my_content_tv);
            holderView.listDeleteTv =
                    (TextView) convertView.findViewById(R.id.my_delete_tv);
            holderView.listRl =
                    (RelativeLayout) convertView.findViewById(R.id.my_rl);
            convertView.setTag(holderView);
        } else {
            holderView = (HolderView) convertView.getTag();
        }

        holderView.listContentTv.setText(mContentsList.get(position));
        holderView.listDeleteTv.setVisibility(visibleDeleteTv.get(position));
        holderView.listSelectCb.setChecked(selectCb.get(position));

        // 整行點擊:展開狀態下再次點擊則復位,否則切換勾選
        holderView.listRl.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (visibleDeleteTv.containsValue(View.VISIBLE)) {
                    resetAll();
                } else {
                    boolean isChecked = !holderView.listSelectCb.isChecked();
                    holderView.listSelectCb.setChecked(isChecked);
                    mContentsDeleteListener
                            .contentsDeleteSelect(position, isChecked);
                }
            }
        });

        holderView.listSelectCb.setOnCheckedChangeListener(
                new OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                                                 boolean isChecked) {
                        mContentsDeleteListener
                                .contentsDeleteSelect(position, isChecked);
                    }
                });

        // 橫向滑動:位移超過 40 時展開刪除按鈕
        convertView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final Animation alpha = AnimationUtils.loadAnimation(
                        mContext, R.anim.anim_right_left);
                int x = (int) event.getX();

                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    alpha.cancel();
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    alpha.cancel();
                    int deltaX = mLastX - x;
                    if (deltaX > 40) {
                        // 先全部復位,再只展開當前項
                        for (int i = 0; i < getCount(); i++) {
                            visibleDeleteTv.put(i, View.GONE);
                            selectCb.put(i, false);
                            mContentsDeleteListener
                                    .contentsDeleteSelect(i, false);
                            if (i == position) {
                                visibleDeleteTv.put(position, View.VISIBLE);
                                selectCb.put(i, true);
                                mContentsDeleteListener
                                        .contentsDeleteSelect(i, true);
                            }
                        }
                        notifyDataSetChanged();
                        if (visibleDeleteTv.get(position) == View.VISIBLE) {
                            holderView.listDeleteTv.startAnimation(alpha);
                        }
                    }
                    return true;   // 消費事件,避免 ListView 攔截做垂直滾動
                } else {
                    alpha.cancel();
                }
                mLastX = x;
                return false;
            }
        });

        holderView.listDeleteTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mContentsList.remove(position);
                mContentsDeleteListener.contentDelete(position);
                resetAll();
                notifyDataSetChanged();
            }
        });

        return convertView;
    }

    /** 把所有項復位為未勾選、按鈕隱藏 */
    private void resetAll() {
        for (int i = 0; i < mContentsList.size(); i++) {
            visibleDeleteTv.put(i, View.GONE);
            selectCb.put(i, false);
            mContentsDeleteListener.contentsDeleteSelect(i, false);
        }
    }

    public class HolderView {
        public TextView listContentTv, listDeleteTv;
        public CheckBox listSelectCb;
        public RelativeLayout listRl;
    }

    /** 與 Activity 通信的接口 */
    public interface ContentsDeleteListener {
        /** 依 isChecked 把指定項加入或移出勾選集合 */
        public void contentsDeleteSelect(int position, boolean isChecked);
        /** 刪除指定位置的數據 */
        public void contentDelete(int position);
    }

    public void setContentsDeleteListener(ContentsDeleteListener l) {
        this.mContentsDeleteListener = l;
    }
    public void setVisibleDeleteTv(Map<Integer, Integer> m) { this.visibleDeleteTv = m; }
    public void setSelectCb(Map<Integer, Boolean> m) { this.selectCb = m; }
}

五、Activity

package com.example.slideandselectdeletedemo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.example.slideandselectdeletedemo.MyAdapter.ContentsDeleteListener;

public class MainActivity extends Activity
        implements ContentsDeleteListener, OnClickListener {

    private ListView myLv;
    private Button myDeleteBtn;
    private MyAdapter myAdapter;
    private String[] myContentsArray;

    private List<String> myContentsList = new ArrayList<String>();
    /** 存放所有被勾選的項,供批量刪除使用 */
    private List<String> mySelectedList = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findById();

        myContentsArray = this.getResources().getStringArray(R.array.my_contents);
        if (myContentsArray != null) {
            Collections.addAll(myContentsList, myContentsArray);
        }

        myAdapter = new MyAdapter(this, myContentsList, this);
        myLv.setAdapter(myAdapter);
    }

    private void findById() {
        myLv = (ListView) this.findViewById(R.id.my_lv);
        myDeleteBtn = (Button) this.findViewById(R.id.my_delete_btn);
        myDeleteBtn.setOnClickListener(this);
    }

    @Override
    public void contentsDeleteSelect(int position, boolean isChecked) {
        String item = myContentsList.get(position);
        if (isChecked) {
            if (!mySelectedList.contains(item)) {
                mySelectedList.add(item);
            }
        } else {
            mySelectedList.remove(item);
        }
    }

    @Override
    public void contentDelete(int position) {
        myContentsList.remove(position);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_delete_btn:
                myContentsList.removeAll(mySelectedList);
                myAdapter.updateView(myContentsList);
                break;
        }
    }
}

關鍵分析與優化建議

mySelectedList 是整個批量刪除的樞紐:它保存的是數據值而非位置索引,這樣在列表發生刪除導致索引位移時,勾選狀態依然正確。這也是原寫法值得借鑒的地方。

不過原始實現仍有幾處可以改進:

  • 用 SparseArray 取代 HashMap。key 是連續整數時,SparseArray 避免了 Integer 的裝箱拆箱,內存與性能都更好,編譯器的 @SuppressLint 提示其實就是在提醒這一點。
  • onTouch 返回 true 會吞掉 ListView 的滾動。更穩健的做法是用 ViewPager 式的滑動容器,或直接在 RecyclerView 上借助 ItemTouchHelper。
  • position 在異步場景下會失效。若列表數據會異步刷新,建議改用 itemId 或數據對象本身作為標識。

在今天的專案中,RecyclerView + ItemTouchHelper + ItemDecoration 是實現側滑刪除的標準方案,能省去大量自定義手勢的邊界處理工作。

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