22

I'm currently trying to add a click listener to the menu hardware button. Currently I'm just putting my onclick logic into the onCreatePanelMenu-method and return false. But that just feels wrong.

Is there a more clean way?

The code currently looks like that:

@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
    Toast.makeText(this, "HALLO!", Toast.LENGTH_SHORT).show();
    return false;
}
schlingel
  • 8,560
  • 7
  • 34
  • 62

4 Answers4

77

Catch the key event inside onKeyDown() and add your action there.

Sample:

@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
    switch(keycode) {
        case KeyEvent.KEYCODE_MENU:
            doSomething();
            return true;
    }

    return super.onKeyDown(keycode, e);
}

Just replace doSomething() with your functionality/methods.

4

If you need some code samples you can try this:

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    switch (item.getItemId())
    {
        case R.id.preferences:
            showPreferencesActivity();
            return true;
        case R.id.logOff:
            logOff();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

The above should be pretty self explanotory - it sets a menu with the options to show preferences or log off.

/Nicklas

Nicklas Møller Jepsen
  • 1,248
  • 2
  • 16
  • 34
1

try this http://developer.android.com/guide/topics/ui/menus.html#ChangingTheMenu

If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu() method

so the system will call onPrepareOptionsMenu() every time the user clicks Menu key

Mohammad Ersan
  • 12,304
  • 8
  • 54
  • 77
0

onContextItemSelected

onOptionsItemSelected

I beleive are what you are looking for.

prolink007
  • 33,872
  • 24
  • 117
  • 185