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;
  ...
}
Thomas S.E.
  • 1,528
  • 16
  • 28

4 Answers4

6

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

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.showOverflowMenu();
marmor
  • 27,641
  • 11
  • 107
  • 150
  • this returns false when I call it – Manny265 Sep 19 '16 at 00:05
  • check the source: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/widget/Toolbar.java#514, 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 '16 at 06: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 '16 at 08:47
  • even better...cheers mate,u should probably make changes to the answer – Manny265 Sep 19 '16 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
duggu
  • 37,851
  • 12
  • 116
  • 113
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);
Lotfi
  • 660
  • 1
  • 6
  • 21
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);
Nanda Gopal
  • 2,519
  • 1
  • 17
  • 25