Android 中ListView带复选框多选、全选、不选处理

转载请注明出处:http://blog.csdn.net/android_koukou/article/details/54290010

Android 中ListView带复选框多选、全选、不选处理
工作快一年了,最近用到ListView带复选框功能,虽然已经做过多次了,但对一些初学者还是有一定的困难,在这里顺便总结一下,供大家参考!!!同时希望大家提出意见!!!!

废话不多说,先看效果

效果一:点击全选,所有复选框选中; 或每个item分别点击选中会触发全选框选中;

效果二:效果一的状态下,随意取消一个item选中状态,此时全选框改变为不选中

效果三:点击全选框为不选中状态,此时所有item为不选中状态

下面是代码部分:

一、首先是activity_main.xml

 version="1.0" encoding="utf-8"?>  
<LinearLayout  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical"  
    tools:context="csttech.com.checkdemo.MainActivity">  

    <CheckBox  
        android:id="@+id/ckb_main"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:background="#666666"  
        android:padding="10dp"  
        android:text="全选"/>  

    <ListView  
        android:id="@+id/list_main"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent">  

    </ListView>  
</LinearLayout>  

二、item.xml格式

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="10dp">

        <TextView
            android:id="@+id/text_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"/>

        <CheckBox
            android:id="@+id/ckb"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:clickable="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </LinearLayout>
</LinearLayout>

三、MainActivity.class

package csttech.com.checkdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;

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

public class MainActivity extends AppCompatActivity {
    private ListView mListView;
    private List<Model> models;
    private CheckBox mMainCkb;
    private MyAdapter mMyAdapter;
    //监听来源
    public boolean mIsFromItem = false;


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

    /**
     * view初始化
     */
    private void initView() {
        mListView = (ListView) findViewById(R.id.list_main);
        mMainCkb = (CheckBox) findViewById(R.id.ckb_main);
    }

    /**
     * 数据加载
     */
    private void initData() {
        //模拟数据
        models = new ArrayList<>();
        Model model;
        for (int i = 0; i < 15; i++) {
            model = new Model();
            model.setSt(i + "******");
            model.setIscheck(false);
            models.add(model);
        }
    }

    /**
     * 数据绑定
     */
    private void initViewOper() {
        mMyAdapter = new MyAdapter(models, this, new AllCheckListener() {

            @Override
            public void onCheckedChanged(boolean b) {
                //根据不同的情况对maincheckbox做处理
                if (!b && !mMainCkb.isChecked()) {
                    return;
                } else if (!b && mMainCkb.isChecked()) {
                    mIsFromItem = true;
                    mMainCkb.setChecked(false);
                } else if (b) {
                    mIsFromItem = true;
                    mMainCkb.setChecked(true);
                }
            }
        });
        mListView.setAdapter(mMyAdapter);
        //全选的点击监听
        mMainCkb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                //当监听来源为点击item改变maincbk状态时不在监听改变,防止死循环
                if (mIsFromItem) {
                    mIsFromItem = false;
                    Log.e("mainCheckBox", "此时我不可以触发");
                    return;
                }

                //改变数据
                for (Model model : models) {
                    model.setIscheck(b);
                }
                //刷新listview
                mMyAdapter.notifyDataSetChanged();
            }
        });

    }
    //对item导致maincheckbox改变做监听
    interface AllCheckListener {
        void onCheckedChanged(boolean b);
    }
}

四、MyAdapter.class

package csttech.com.checkdemo;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import java.util.List;

/**
 * Created by zhaiydong on 2017/1/9.
 */
public class MyAdapter extends BaseAdapter {
    private List<Model> data;
    private Context context;
    private MainActivity.AllCheckListener allCheckListener;

    public MyAdapter(List<Model> data, Context context, MainActivity.AllCheckListener allCheckListener) {
        this.data = data;
        this.context = context;
        this.allCheckListener = allCheckListener;
    }

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

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

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

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        ViewHoder hd;
        if (view == null) {
            hd = new ViewHoder();
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            view = layoutInflater.inflate(R.layout.item_list, null);
            hd.textView = (TextView) view.findViewById(R.id.text_title);
            hd.checkBox = (CheckBox) view.findViewById(R.id.ckb);
            view.setTag(hd);
        }
        Model mModel = data.get(i);
        hd = (ViewHoder) view.getTag();
        hd.textView.setText(mModel.getSt());

        Log.e("myadapter", mModel.getSt() + "------" + mModel.ischeck());
        final ViewHoder hdFinal = hd;
        hd.checkBox.setChecked(mModel.ischeck());
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckBox checkBox = hdFinal.checkBox;
                if (checkBox.isChecked()) {
                    checkBox.setChecked(false);
                    data.get(i).setIscheck(false);
                } else {
                    checkBox.setChecked(true);
                    data.get(i).setIscheck(true);
                }
                //监听每个item,若所有checkbox都为选中状态则更改main的全选checkbox状态
                for (Model model : data) {
                    if (!model.ischeck()) {
                        allCheckListener.onCheckedChanged(false);
                        return;
                    }
                }
                allCheckListener.onCheckedChanged(true);


            }
        });


        return view;
    }

    class ViewHoder {
        TextView textView;
        CheckBox checkBox;
    }

}

五、Model

package csttech.com.checkdemo;

/**
 * Created by zhaiydong on 2017/1/9.
 */
public class Model {
    private boolean ischeck;
    private String st;

    public boolean ischeck() {
        return ischeck;
    }

    public void setIscheck(boolean ischeck) {
        this.ischeck = ischeck;
    }

    public String getSt() {
        return st;
    }

    public void setSt(String st) {
        this.st = st;
    }
}

demo下载地址:http://download.csdn.net/detail/android_koukou/9733420

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要在Qt ListView添加复选框并实现全选功能,需要执行以下步骤: 1. 创建一个自定义的QAbstractListModel或QStandardItemModel来作为数据模型。 2. 在数据模型添加一个bool类型的属性来表示每个项目是否选。 3. 在ListView的delegate添加一个QCheckBox来显示每个项目的选状态。 4. 创建一个全选/取消全选按钮并连接到相应的槽函数。 5. 在槽函数遍历所有项目并设置它们的选状态。 以下是一个示例代码: ``` // 自定义数据模型 class MyModel : public QAbstractListModel { public: struct Item { QString name; bool selected; }; MyModel(QObject *parent = nullptr) : QAbstractListModel(parent) {} int rowCount(const QModelIndex &parent = QModelIndex()) const override { return m_items.count(); } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { if (!index.isValid() || index.row() >= m_items.count()) return QVariant(); if (role == Qt::DisplayRole || role == Qt::EditRole) return m_items.at(index.row()).name; if (role == Qt::CheckStateRole) return m_items.at(index.row()).selected ? Qt::Checked : Qt::Unchecked; return QVariant(); } Qt::ItemFlags flags(const QModelIndex &index) const override { if (!index.isValid() || index.row() >= m_items.count()) return Qt::NoItemFlags; return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsUserCheckable; } bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override { if (!index.isValid() || index.row() >= m_items.count()) return false; if (role == Qt::CheckStateRole) { m_items[index.row()].selected = value.toBool(); emit dataChanged(index, index, {role}); return true; } if (role == Qt::EditRole) { m_items[index.row()].name = value.toString(); emit dataChanged(index, index, {role}); return true; } return false; } QList<Item> items() const { return m_items; } void setItems(const QList<Item> &items) { beginResetModel(); m_items = items; endResetModel(); } void selectAll(bool selected) { for (int i = 0; i < m_items.count(); ++i) { if (m_items[i].selected != selected) { m_items[i].selected = selected; emit dataChanged(index(i), index(i), {Qt::CheckStateRole}); } } } private: QList<Item> m_items; }; // ListView的delegate class MyDelegate : public QStyledItemDelegate { public: MyDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {} QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override { QCheckBox *checkBox = new QCheckBox(parent); checkBox->setCheckState(index.data(Qt::CheckStateRole).toBool() ? Qt::Checked : Qt::Unchecked); return checkBox; } void setEditorData(QWidget *editor, const QModelIndex &index) const override { QCheckBox *checkBox = qobject_cast<QCheckBox *>(editor); checkBox->setCheckState(index.data(Qt::CheckStateRole).toBool() ? Qt::Checked : Qt::Unchecked); } void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override { QCheckBox *checkBox = qobject_cast<QCheckBox *>(editor); model->setData(index, checkBox->isChecked(), Qt::CheckStateRole); } }; // MainWindow的代码 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // 创建数据模型并设置ListView的model和delegate m_model = new MyModel(this); ui->listView->setModel(m_model); ui->listView->setItemDelegate(new MyDelegate(this)); // 添加测试数据 QList<MyModel::Item> items; items.append({"Item 1", false}); items.append({"Item 2", false}); items.append({"Item 3", false}); items.append({"Item 4", false}); m_model->setItems(items); // 创建全选/取消全选按钮并连接到槽函数 QPushButton *selectAllButton = new QPushButton("Select All", this); ui->mainToolBar->addWidget(selectAllButton); connect(selectAllButton, &QPushButton::clicked, this, &MainWindow::onSelectAllClicked); } void MainWindow::onSelectAllClicked() { m_model->selectAll(true); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值