Question

I'd like to be able to show a toast or dialog or other options instead of displaying a menu sometimes, if the menu button is pressed.

I tried this, but of course it doesn't work since onCreateOptionsMenu is called when the Activity is first loaded, not when the Menu key is disabled. Is there any way to do what I'm trying to do?

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   if (disableMenu())
      Toast.makeText(this, R.string.no_menu_for_you, Toast.LENGTH_LONG).show();
}

edit: I added the .show() so that people wouldn't focus on that part. This is not what's causing the issue.

Was it helpful?

Solution

You forgot .show() and you should use onPrepareOptionsMenu, which is called every time the menu button is pressed.

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
   super.onPrepareOptionsMenu(menu);

   if (disableMenu())
      Toast.makeText(this, R.string.no_menu_for_you, Toast.LENGTH_LONG).show();

   return true;
}

OTHER TIPS

You forgot to call show():

 Toast.makeText(this, R.string.no_menu_for_you, Toast.LENGTH_LONG).show();

EDIT :

As you want to capture the click of a menu buttin, I guess this will work but I didn't try it:

protected boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_MENU) {
         // When Menu Key is pressed
         Toast.makeText(this, R.string.no_menu_for_you, Toast.LENGTH_LONG).show();
         return true;
     }
     return false;
 }

Call .show() for showing Toast as

Toast.makeText(this, R.string.no_menu_for_you, Toast.LENGTH_LONG).show();

instead of

Toast.makeText(this, R.string.no_menu_for_you, Toast.LENGTH_LONG);

you forgot to call show() on your toast.

if this doesn't help try to return true in your onCreateOptionsMenu(Menu menu) and then implement your menu behaviour in onOptionsItemSelected(MenuItem item).

You forgot to call show() method which is required to show the toast.

And to perform any action on menu button,you can use the following way.

Override the onKeyDown(int keyCode, KeyEvent event)method like i did .

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) 

        case KeyEvent.KEYCODE_MENU:

        Toast.makeText(getApplicationContext(),"Menu key Pressed", 3000).show();    

            break;  
        }


                return false;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top