关于listview的全选、反选、取消、删除等操作

一般listview的每个item都有点击事件,一个item一个点击事件是没有问题的。

当一个item中出现多个点击效果时,并且还要保留item的点击效果,我们该怎么处理呢?

这时我们需要用到这个属性(一般写在item的布局上)

这个属性的作用就是:阻止焦点向子控件传递。

android:descendantFocusability="blocksDescendants"

单个控件时使用:

android:focusable="false"

这个需要注意一下,Demo如下:

Activity布局:

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
        <Button
            android:id="@+id/mBt_all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全选"
            android:onClick="onClick"
            android:textColor="#0000ff"
            android:background="@color/colorAccent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            />
        <Button
            android:id="@+id/mBt_un_all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="反选"
            android:onClick="onClick"
            android:textColor="#0000ff"
            android:background="@color/colorAccent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            />
        <Button
            android:id="@+id/mBt_cancle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="取消"
            android:onClick="onClick"
            android:textColor="#0000ff"
            android:background="@color/colorAccent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            />
        <Button
            android:id="@+id/mBt_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="删除"
            android:onClick="onClick"
            android:textColor="#0000ff"
            android:background="@color/colorAccent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            />
    </LinearLayout>

    <ListView
        android:id="@+id/mListView"
        android:overScrollMode="never"
        android:divider="@color/colorAccent"
        android:dividerHeight="0.1dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</LinearLayout>

item布局:

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:descendantFocusability="blocksDescendants"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp">

    <TextView
        android:id="@+id/mTe_item"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_margin="5dp"
        android:layout_centerVertical="true"
        />
    <CheckBox
        android:id="@+id/mCb_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        />

</RelativeLayout>

完整代码:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    private List<String> list;
    private List<Boolean> checks;
    private ListView listView;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.mListView);
//     添加数据
        initData();
    }

    private void initData() {
        list = new ArrayList<>();
        checks = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            list.add("数据"+i);
            checks.add(false);
        }
        adapter = new MyAdapter(this, list);
        adapter.setData(list, checks);
        listView.setAdapter(adapter);

//        条目点击
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "item点击了", Toast.LENGTH_SHORT).show();
                checks.set(position, !checks.get(position));
                adapter.setData(list, checks);
                adapter.notifyDataSetChanged();
            }
        });

    }
//       按钮点击
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mBt_all:
                select_All();
                break;
            case R.id.mBt_un_all:
                select_UnAll();
                break;
            case R.id.mBt_cancle:
                select_cancle();
                break;
            case R.id.mBt_delete:
                select_delete();
                break;
        }
    }

    //      删除
    private void select_delete() {
        for (int i = 0; i < checks.size(); i++) {
//            判断是否选中,清除多选按钮,数据,以及索引
            if (checks.get(i)) {
                checks.remove(i);
                list.remove(i);
                i--;
            }
            adapter.setData(list, checks);
            adapter.notifyDataSetChanged();
        }
    }

    //  取消
    private void select_cancle() {
        for (int i = 0; i < checks.size(); i++) {
            checks.set(i, false);
        }
        adapter.setData(list, checks);
        adapter.notifyDataSetChanged();
    }

    //  反选
    private void select_UnAll() {
        for (int i = 0; i < checks.size(); i++) {
            checks.set(i, !checks.get(i));
        }
        adapter.setData(list, checks);
        adapter.notifyDataSetChanged();
    }

    //全选
    private void select_All() {
        for (int i = 0; i < checks.size(); i++) {
            checks.set(i, true);
        }
        adapter.setData(list, checks);
        adapter.notifyDataSetChanged();
    }
}

Adapter:

public class MyAdapter extends BaseAdapter {
    private Context mContext;
    private List<String> mList;
    private List<Boolean> checks;
    public MyAdapter(Context mContext, List<String> mList) {
        this.mContext = mContext;
        this.mList = mList;
    }

    public void setData(List<String> mList,List<Boolean> checks) {
        this.mList = mList;
        this.checks = checks;
    }

    @Override
    public int getCount() {
        return mList==null?0:mList.size();
    }

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

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
            convertView= View.inflate(mContext,R.layout.layout_listeitem,null);
        ViewHolder viewHolder = ViewHolder.getViewHolder(convertView);
        viewHolder.textView.setText(mList.get(position));
        viewHolder.checkBox.setChecked(checks.get(position));

        viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checks.set(position,isChecked);
                notifyDataSetChanged();
            }
        });
        return convertView;
    }

    static class ViewHolder{
        private TextView textView;
        private CheckBox checkBox;

        public ViewHolder(View convertView){
            textView=convertView.findViewById(R.id.mTe_item);
            checkBox=convertView.findViewById(R.id.mCb_item);
        }

        public static ViewHolder getViewHolder(View convertView){
            ViewHolder viewHolder= (ViewHolder) convertView.getTag();
            if (viewHolder==null){
                viewHolder=new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            }
            return viewHolder;
        }

    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在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); } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值