44

I have these menu items in my menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item android:id="@+id/action_restart" android:title="Restart"
        android:orderInCategory="1" />
    <item android:id="@+id/action_clear" android:title="Clear"
        android:orderInCategory="2" />
    <item android:id="@+id/action_update" android:title="Update"
        android:orderInCategory="3" />
    <item android:id="@+id/action_about" android:title="About"
        android:orderInCategory="4" />
    <item android:id="@+id/action_try_restart" android:title="Try Restart"
        android:orderInCategory="5" />
</menu>

And I have this in my onOptionsItemSelected method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_restart) {
        Toast.makeText(MainActivity.this, "Restart...", Toast.LENGTH_LONG).show();
    }

    if (id == R.id.action_clear) {
        Toast.makeText(MainActivity.this, "Clear...", Toast.LENGTH_LONG).show();
    }

    if (id == R.id.action_update) {
        Toast.makeText(MainActivity.this, "Update...", Toast.LENGTH_LONG).show();
    }

    if (id == R.id.action_about) {
        Toast.makeText(MainActivity.this, "About...", Toast.LENGTH_LONG).show();
    }

    if(id == R.id.action_try_restart) {
        // how to click / trigger the "action_restart" from here?
    }

    return super.onOptionsItemSelected(item);
}

I have tried with:

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

But actionRestart reference doesn't offer anything like click, trigger, etc.

I'd also like to note that I'm new to Android development and I come from PHP/JavaScript background, so this level of Java OOP is all new to me.

9 Answers 9

56

Use the method performIdentifierAction, like this:

menu.performIdentifierAction(R.id.action_restart, 0);
5
  • How can I get the [menu] from activity's [onCreate]? Commented Apr 18, 2019 at 21:17
  • 2
    @p2lem8dev, you can get the menu in public boolean onCreateOptionsMenu(Menu menu)
    – Simon
    Commented Apr 19, 2019 at 22:11
  • exactly what I need Commented Apr 3, 2020 at 12:09
  • This is actually works for me ,Thank you . Commented Feb 12, 2022 at 1:22
  • Great! :) It's also work for NavigationView Menu and MenuItem. Thanks!
    – Victor
    Commented Nov 28, 2022 at 14:49
17

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

MenuItem actionRestart = (MenuItem) findViewById(R.id.action_restart);
onOptionsItemSelected(actionRestart);
4
  • 2
    I will try this too! I've made a separate method, as I have described in Veselin Romic's answer up above. Thank you too. Commented May 2, 2015 at 12:59
  • 5
    java.lang.ClassCastException: android.support.v7.view.menu.ActionMenuItemView cannot be cast to android.view.MenuItem Commented Aug 4, 2016 at 12:54
  • In my case it throws exception when I try to find the view in [onCreate] method. How can I get there? Commented Apr 18, 2019 at 21:19
  • the method findViewById() returns null in onCreate() method. Where the code should be put?
    – eastwater
    Commented Jul 14, 2020 at 23:38
10

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.

2
  • 1
    you can use the method performIdentifierAction
    – Simon
    Commented Aug 15, 2017 at 22:45
  • see @VadymVL answer, it is purely possible
    – Umar Ata
    Commented Sep 1, 2018 at 10:03
10

I would like to share my solution as well here. Instead of trying to click programmatically a menu item, I created a separate method for menu item click, and call it anywhere where I need to click menu item. OnOptionsItemSelected method looks as follows. As you can see I moved click logic to a separate method.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        homeClicked();
    }
    return super.onOptionsItemSelected(item);
}
private void homeClicked(){
    ...
}

Now you can call homeClicked anytime you need to click menu item programmatically.

1
  • 1
    nice approach as we don't have native method
    – MilapTank
    Commented Jul 19, 2017 at 6:53
6

Even though it's not the best way to do,

MenuItem item_your_choice;

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.your_menu, menu);
    item_your_choice = menu.findItem(R.id.item_your_choice);
    return super.onCreateOptionsMenu(menu);
}

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case item_your_choice:
           //do whatever you want
            break;
        }
   return super.onOptionsItemSelected(item);
}

just Call from any method

onOptionsItemSelected(item_you_choice);
4
  1. Make global Menu

    public Menu mMenu;
    
  2. Assign menu to mMenu while override onCreateOptionMenu

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        this.mMenu = menu;
        return super.onCreateOptionsMenu(menu);
    }
    
  3. Call event like this:

    if(mMenu != null) {
        MenuItem action = mMenu.findItem(R.id.action_restart);
    
        if(action != null) {
            onOptionsItemSelected(action);
        }
    }
    
0
2

As per your example for menu item above :

<item android:id="@+id/action_restart" android:title="Restart"
        android:orderInCategory="1" />

use callOnClick() method :

((ActionMenuItemView)findViewById(R.id.action_restart)).callOnClick();
0
2

Not sure if this is the best way, but here is how I did it.

BottomNavigationItemView has the method callOnClick().

BottomNavigationItemView menuItem = findViewById(R.id.navigation_take_post);
menuItem.callOnClick();
-3

There is a standard method to do this -
Create a new instance of MenuItem class and change the overridden method getItemId() to return the id of desired menu item and leave the rest unchanged.

MenuItem actionRestart = new MenuItem() {
                                             @Override
                                             public int getItemId() {
                                               return R.id.action_restart;
                                             }

                                             ...

                                           };
onOptionsItemSelected(actionRestart);
1
  • 1
    This will override all of the MenuItem's interface method, which makes your code messy
    – emen
    Commented Nov 29, 2016 at 2:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.