How to programmatically trigger/click on a MenuItem in Android?

Use the method performIdentifierAction, like this:

menu.performIdentifierAction(R.id.action_restart, 0);

As far as I know, there is no mechanism in the SDK that lets you do this. It's certainly not standard practice to do this sort of thing.

I recommend decoupling your logic from the actual UI as much as possible, so you end up not needing to simulate a click to trigger the action. Since you're a Web developer, this should come fairly easily to you.

In this case, you'd want to refactor the toasts into a separate method (or multiple methods), and then call that both when the menu item is clicked and when you want to trigger it manually.

Alternatively, you could try taking the MenuItem returned by findViewById() and passing it to your handler there. But I have no idea if that'll work.


You should manually call your listener, with required item as parameter.

MenuItem actionRestart = (MenuItem) findViewById(R.id.action_restart);
onOptionsItemSelected(actionRestart);