Q:

Handling checkbox event in option menu : Android

I have a menu that has checkbox menu item type and whenever i check it. It doesn't trigger anything. Here is my 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>

Here is my 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);
    }
}

Any idea?

A:

You can handle CheckBox click inside onCreateOptionsMenu by listen setOnCheckedChangeListener like this
@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;
}

And remember change android:actionViewClass="android.widget.CheckBox" to app:actionViewClass="android.widget.CheckBox"

