I am making an app for android. When the user clicks on the device's hardware menu button, I want to open a custom popup menu which has options pertaining to my activity. According to android documentation, only context menu and options menu can be made, and there is no way to access the hardware menu button's functions. How to do this?
2 Answers
Newer Android devices (running 3.0+) are no longer required to have a hardware menu button (source). You can create a menu following this tutorial. When you create an options menu, the app will let the user open it with the hardware menu button if their device has one. If it doesn't, then a menu button will be displayed in the Action bar. (source).
If you for whatever reason need to detect pressing the menu button, you can do it by overriding the onKeyUp(int, KeyEvent)
method of your Activity
.
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
// do stuff
return true;
} else {
return super.onKeyUp(keyCode, event);
}
}
If you need to open the menu from within your code, you can call the Activity.openOptionsMenu()
method.
-
Ok, and how to add options to the menu? – vergil corleone May 07 '13 at 17:37
-
Please check the edited (actually, almost completely new :)) answer. – zbr May 07 '13 at 18:22
My answer is totally based on http://developer.android.com/guide/topics/ui/menus.html
Please read that page for full info, description and more knowledge about how to do this
Create an XML:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ic_new_game"
android:title="@string/new_game"
android:showAsAction="ifRoom"/>
<item android:id="@+id/help"
android:icon="@drawable/ic_help"
android:title="@string/help" />
</menu>
Use this code to show it:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
Use this code to handle clicks:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

- 3,140
- 2
- 26
- 41