How to programmatically trigger/click on a MenuIte

2019-02-05 19:56发布

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.

8条回答
倾城 Initia
2楼-- · 2019-02-05 20:34

Use the method performIdentifierAction, like this:

menu.performIdentifierAction(R.id.action_restart, 0);
查看更多
别忘想泡老子
3楼-- · 2019-02-05 20:39
  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);
        }
    }
    
查看更多
登录 后发表回答