在选项菜单中处理复选框事件:Android

5

我有一个菜单,其中包含复选框菜单项类型,每当我勾选它时,它不会触发任何操作。以下是我的menu.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/delete"
    android:actionViewClass="android.widget.CheckBox"
    android:checkableBehavior="single"
    android:title="All"
    android:titleCondensed="All"
    app:showAsAction="ifRoom"></item>
</menu>

这是我onOptionsItemSelected函数的代码。
  @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.delete:
            Toast.makeText(this,"Hello",Toast.LENGTH_SHORT).show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

有什么想法吗?
1个回答

7

您可以通过监听setOnCheckedChangeListeneronCreateOptionsMenu内处理复选框的单击事件,如下所示:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    CheckBox checkBox = (CheckBox) menu.findItem(R.id.delete).getActionView();
    checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // perform logic
            }
        }
    });

    return true;
}

请记得将android:actionViewClass="android.widget.CheckBox"更改为app:actionViewClass="android.widget.CheckBox"

(涉及技术:Android开发)

似乎在设置 OnCheckedChangeListener 对象时,checkBox 为空。导致出现:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference。 - shadygoneinsane
可以了,谢谢。你有没有想过如何将上下文操作栏的后退按钮改为复选框?比如长按列表视图后会显示一个全选复选框。 - Meowok
@shadygoneinsane 谢谢你纠正我,麻烦再次检查我的答案。 - Linh
@Meowok 我认为这是一个不同的问题,你应该添加新的问题。如果你认为我的回答解决了你的问题,请将其标记为正确答案。谢谢。 - Linh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接