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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With