2

I need to open the (overflow) menu programmatically on click of the home button.

As in other topics provided I have tried Activity.openOptionsMenu() and ActionBarActivity().getSupportActionBar().openOptionsMenu() but both times nothing happens.

Used Code:

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
  ...
     case android.R.id.home:
        Log.i("HOME", "clicked");

        this.openOptionsMenu();
        break;
  ...
}
4

4 Answers 4

6

If you're using the new Toolbar class of the Support Library, do this:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.showOverflowMenu();
4
  • this returns false when I call it
    – Manny265
    Sep 19, 2016 at 0:05
  • check the source: android.googlesource.com/platform/frameworks/base/+/refs/heads/…, are you sure you've properly set a menu to the toolbar? and that you're seeing an overflow button on the toolbar (3 dots)?
    – marmor
    Sep 19, 2016 at 6:47
  • 1
    it means there's a race condition between inflating the toolbar, and your request to show the menu. try this: toolbar.post(new Runnable() { public void run() { toolbar.showOverflowMenu(); } });
    – marmor
    Sep 19, 2016 at 8:47
  • even better...cheers mate,u should probably make changes to the answer
    – Manny265
    Sep 19, 2016 at 21:13
1

I achieve to do below thing hopefully help you also :-

// R.id.over_flow_item this your id in which your task has been perform
toolbar.getMenu().perperformIdentifierAction(R.id.over_flow_item,0);

perperformIdentifierAction

public abstract boolean performIdentifierAction (int id, int flags)
Added in API level 1
Execute the menu item action associated with the given menu identifier.
Parameters
id
Identifier associated with the menu item.
flags
Additional option flags or 0.
Returns
If the given identifier exists and is shown, returns true; else returns false.
See Also
FLAG_PERFORM_NO_CLOSE
0

If you don't have an ActionBar, the only way I found is to simulate a KeyEvent. This makes the options menu appears

    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

If you are using customized toolbar in you app, you can use the following way,

 new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    toolbar.showOverflowMenu();
                }
            }, 500);

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.