How to open the options menu programmatically?

前端 未结 11 1576
时光说笑
时光说笑 2020-11-28 06:47

I would like to open the optionsMenu programmatically without a click on the menu key from the user. How would I do that?

相关标签:
11条回答
  • 2020-11-28 06:53

    Two ways to do it:

    Activity.getWindow().openPanel(Window.FEATURE_OPTIONS_PANEL, event);
    

    The event argument is a KeyEvent describing the key used to open the menu, which can modify how the menu is displayed based on the type of keyboard it came from.

    Or... by simulating that the user has pressed the button:

    IWindowManager wManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
    KeyEvent kd = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SOFT_LEFT);
    KeyEvent ku = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SOFT_LEFT);
    wManager.injectKeyEvent(kd.isDown(), kd.getKeyCode(), kd.getRepeatCount(), kd.getDownTime(), kd.getEventTime(), true);
    
    0 讨论(0)
  • 2020-11-28 06:57

    Apparently, doing it in onCreate breaks app, since Activity's not yet attached to a window. If you do it like so:

    @Override
    public void onAttachedToWindow() {
        openOptionsMenu(); 
    };
    

    ...it works.

    0 讨论(0)
  • 2020-11-28 07:00

    For me, declaring toolbar.showOverflowMenu() in onClick is not worked. openOptionsMenu() also not worked for me. Instead of that the following way is worked for me,

    new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    toolbar.showOverflowMenu();
                }
            }, 500);
    
    0 讨论(0)
  • 2020-11-28 07:04

    from an OnClickListener inside an activity called MainActivity:

    MainActivity.this.openOptionsMenu();
    
    0 讨论(0)
  • 2020-11-28 07:09

    After a long research and many tries, the only way seems to be simulating a KeyEvent. This makes the options menu appear:

    BaseInputConnection mInputConnection = new BaseInputConnection( findViewById(R.id.main_content), true);
    KeyEvent kd = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU);
    KeyEvent ku = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU);
    mInputConnection.sendKeyEvent(kd);
    mInputConnection.sendKeyEvent(ku);
    
    0 讨论(0)
  • 2020-11-28 07:10

    If you are inside an your view, you can write

        ((Activity)getContext()).openOptionsMenu();
    
    0 讨论(0)
提交回复
热议问题