Android,可检查的菜单项

时间:2015-09-25 20:53:09

标签: java android menu android-actionbar checked

我的ActionBar中有一个菜单,可以检查(用XML格式),但是当我尝试在java中按下这个项目检查它时,项目保持未选中状态(但与此操作相关的其他内容是完成)

我的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"
    xmlns:tools="http://schemas.android.com/tools">
    [...]
    <item
        android:id="@+id/menu_switch_full_original"
        android:title="@string/menu_switch_full_original"
        android:checkable="true"/>
</menu>

和java代码:

public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        Activity activity = getActivity();

        switch (item.getItemId()) {
            [...]
            case R.id.menu_switch_full_original: {
                item.setChecked(true);
                [...]
        }
        activity.invalidateOptionsMenu();
    }
    return true;
}

我错过了什么?

1 个答案:

答案 0 :(得分:3)

试试这个......

private boolean isChecked = false;

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
         MenuItem checkable = menu.findItem(R.id.menu_switch_full_original);
         checkable.setChecked(isChecked);
         return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        getMenuInflater().inflate(R.menu.a, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case R.id.menu_switch_full_original:
            isChecked = !item.isChecked();
            item.setChecked(isChecked);
            // your other functionality
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }