android完美解决ListView中CheckBox的全选、反选、批量删除的问题

效果图


前几天看到有朋友发帖问关于ListView的多选、反选、取消等问题,我自己想了一下,最好的解决方法应该是生成一个list来维系checkbox组的选择状态。利用listview的getChildAt方法来获得当前状态会有很多很多的问题,所以不建议采用。

另外,本文来增加了一个关于被选择的checkbox删除的功能,供大家参考

思路

  1. 利用SparseArray<Boolean> checkBoxStates作为一个记录checkbox组状态的组合
  2. 全选、反选、取消动作将会影响checkBoxStates中的值,并触发adapter.notifyDataSetChanged()
  3. 用户单击checkbox行为将触发onCheckedChangeListener
  4. 删除动作会有一点复杂,会有一些细节要注意,请看下面代码的注释
  5. 要分清keyAt(int index)和get(int key)、put(int key,boolean state)和setValueAt(int index,boolean state)的区别
package com.example.yuanh.checkboxtest;

import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    SparseArray checkStates;
    RecyclerView listView;
    MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initDate();
        findViewById(R.id.select_all).setOnClickListener(this);
        findViewById(R.id.reverse).setOnClickListener(this);
        findViewById(R.id.cancel_all).setOnClickListener(this);
        findViewById(R.id.init).setOnClickListener(this);
        findViewById(R.id.delete).setOnClickListener(this);
        listView = (RecyclerView) findViewById(R.id.listView);
        adapter = new MyAdapter();
        listView.setAdapter(adapter);
        listView.setLayoutManager(new LinearLayoutManager(this));
        listView.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_all:
                selectAll();
                break;
            case R.id.reverse:
                reverse();
                break;
            case R.id.cancel_all:
                cancelAll();
                break;
            case R.id.init:
                initDate();
                adapter.notifyDataSetChanged();
                break;
            case R.id.delete:
                delete();
                break;
        }
    }

    private void delete() {
        for (int i=0;iif (checkStates.valueAt(i)){
                checkStates.delete(checkStates.keyAt(i));
//                当前的项已被删除,记得i要自减,否则会出现混乱
                i--;
            }
        }
        adapter.notifyDataSetChanged();
    }

//    取消所有选择
    private void cancelAll() {
        Log.v("check", listView.getChildCount() + "");
        for (int i = 0; i < checkStates.size(); i++) {
            checkStates.setValueAt(i, false);
        }
        adapter.notifyDataSetChanged();
    }

//    反选
    private void reverse() {
        for (int i = 0; i < checkStates.size(); i++) {
            if (checkStates.valueAt(i)) {
                checkStates.setValueAt(i, false);
            } else {
                checkStates.setValueAt(i, true);
            }
        }
        adapter.notifyDataSetChanged();
    }

//    全选
    private void selectAll() {
        for (int i = 0; i < checkStates.size(); i++) {
            checkStates.setValueAt(i, true);
        }
        adapter.notifyDataSetChanged();
    }

//    初始化
    private void initDate() {
        checkStates = new SparseArray<>();
        for (int i = 0; i < 30; i++) {
            checkStates.put(i, false);
        }
    }

    private class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.item,parent,false);
            MyViewHolder  holder = new MyViewHolder(v);
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position) {

            holder.checkBox.setText(checkStates.keyAt(position)+"");
            holder.checkBox.setChecked(checkStates.valueAt(position));

//            用户点击checkbox行为会需要增加监听来改变checkStates对应项的状态
            holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Log.v("check",position+":"+isChecked);
                    checkStates.setValueAt(position, isChecked);
                }
            });
        }

        @Override
        public int getItemCount() {
            return checkStates.size();
        }
    }

    private class MyViewHolder extends RecyclerView.ViewHolder{
        public CheckBox checkBox;
        public MyViewHolder(View itemView) {
            super(itemView);
            checkBox = (CheckBox)itemView.findViewById(R.id.checkBox);
        }
    }
}

你可能感兴趣的:(android)