jeudi 29 mars 2018

android OptionsMenu checkable item: change without clicking

I have an options menu which contains one checkable item besides other items.

This is how I set that item checked and store the value inside onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.action_uploadCurrList) {
        return true;
    } else if (id == R.id.action_downloadCurrList) {
        return true;
    } else if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_sort_cat) {
        item.setChecked(!item.isChecked());
        catSort = item.isChecked();
        saveSortState(catSort);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

The value of catSort is set inside onCreateOptionsMenu. That's working fine.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_shopping_list, menu);
    menu.findItem(R.id.action_sort_cat).setChecked(catSort);
    return true;
}

But now, I want to update the isChecked() of that menu item if catSort changed at runtime. I want to do that before the user opens menu. How can I do that? It seems like I can't call setChecked() anywhere else but I have to update that checkbox if my boolean variable changes.




Aucun commentaire:

Enregistrer un commentaire