Robert Granat
Robert Granat

Reputation: 211

Set a menu item as checked from code

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?

Upvotes: 21

Views: 32331

Answers (2)

Keyur Sureliya
Keyur Sureliya

Reputation: 164

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. :)

Upvotes: 6

Michael
Michael

Reputation: 54705

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;
}

Upvotes: 56

Related Questions