Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Programmatically select menu option

Tags:

android

Is there a way to programmatically select a menu option? Basically, I want a button in a view to perform the same action as pressing a specific menu option. I was thinking of trying to call onOptionsItemSelected(MenuItem item) but I don't know what to put for the menu item.

like image 815
dt0 Avatar asked Nov 28 '12 22:11

dt0


2 Answers

Yes there is a way to select a menu option! And you are right about calling onOptionsItemSelected(MenuItem item) here is the way to get the MenuItem:

1) first thing you need to do is get the reference of the Menu class inside your Activity here:

private Menu menu;

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
   this.menu = menu;
   return super.onCreateOptionMenu(menu);
}

2) So basically, the Menu class contains all your menu items. So once you have this reference, you simulate the menu click like this:

onOptionsItemSelected(menu.findItem(R.id.action_id));

...where action_id is the id of the menu item you want to select. you can find this id in your menu xml.

like image 81
Lemuel Avatar answered Sep 20 '22 09:09

Lemuel


I was also looking for this. and while it makes sense to call the method used when an item gets checked, that will not set the menu item as checked in the UI.

So what I ended up doing was:

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

MenuItem menuItem = (MenuItem)navigationView.getMenu().findItem(R.id.nav_menu_item_1);
        menuItem.setChecked(true);
        onNavigationItemSelected(menuItem);

The following did not work as desired for me:

onOptionsItemSelected(menu.findItem(R.id.action_id));

like image 25
Heriberto Lugo Avatar answered Sep 19 '22 09:09

Heriberto Lugo