Set a menu item as checked from code

巧了我就是萌 提交于 2019-12-03 05:54:55

问题


I have an Android application with the following menu item in one of the Activities (which concerns handling a list of names and mac numbers):

<item android:id="@+id/menu_sort_tagg"
      android:icon="@android:drawable/ic_menu_sort_by_size"
      android:title="@string/menu_sort_list" >
      <menu> 
        <group android:checkableBehavior="single">
            <item android:id="@+id/sort_by_name"
                  android:title="@string/sort_by_name" />
            <item android:id="@+id/sort_by_mac"
                          android:title="@string/sort_by_mac" />

     </menu>
</item>

and as the application state changes, I want to be able to pre-check which item in the sort options list that was used last time with the following code:

((MenuItem)findViewById(R.id.sort_by_name)).setChecked(true);

The problem is that this specific line gives me a runtime exception. Does anyone have a clue why?

A look at the log reveals that the runtime exceptions is triggered by a null pointer exception. By changing the code in this way:

MenuItem mi = (MenuItem)findViewById(R.id.sort_by_name);
mi.setChecked(true);

it becomes clear that the exception occurs in the seconds statement, i.e., the MenuItem mi is null. So why fails the first statement to bring a pointer to the correct MenuItem?


回答1:


You can't do findViewById() for a menu, because it's a menu, not a view. And you can change menu state when it's being created or prepared. For example, if you create an options menu, you can do it in the Activity: onPrepareOptionsMenu() method:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    menu.findItem(R.id.sort_by_name).setChecked(true);
    //Also you can do this for sub menu
    menu.getItem(firstItemIndex).getSubMenu().getItem(subItemIndex).setChecked(true);
    return true;
}



回答2:


private boolean _isHidden = false;

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId())
    {
        case R.id.hiddenfiles:
            if(!_isHidden)
            {
                _isHidden = true;
                item.setChecked(true);
            }
            else {
                _isHidden = false;
                item.setChecked(false);
            }
    }

    return super.onOptionsItemSelected(item);
}
  • You can use this code one or multiple menuitems.

  • Just use 'item' from 'public boolean onOptionsItemSelected(MenuItem item)'

  • I used this, which worked for me. :)



来源:https://stackoverflow.com/questions/6150080/set-a-menu-item-as-checked-from-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!