Adding an “options menu” to an Android app’s Activity
is quite simple.
This is an example of what an Android options menu looks like. Look at the icon that looks like 3 dots vertically stacked.
My dev environment status as of writing this
Android Studio version: v. 2.1
OS: Mac OS X El Capitan v. 10.11
My Android app build status:
- compileSdkVersion: 24
- buildToolsVersion: 24.0.2
- minSdkVersion: 16
- targetSdkVersion: 24
Add “options menu” to an Android AppCompatActivity
#1 Create menu layout file
Create res/menu/main.xml
, creating the menu
folder if not yet existing.
Add the following to res/menu/main.xml
:
1 2 3 4 5 6 7 |
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/about" android:title="About" /> <item android:id="@+id/help" android:title="Help" /> </menu> |
#2 Enable menu by adding MenuInflater to the Activity
Add the following overriding method to your AppCompatActivity
:
1 2 3 4 5 6 |
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } |
#3 Add listener for selected options menu item
Again, add the following overriding method to your AppCompatActivity
. Replace the Toasts with whatever you need to do upon menu item selection:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about: Toast.makeText(MainActivity.this, "Selected options menu item: About", Toast.LENGTH_SHORT).show(); return true; case R.id.help: Toast.makeText(MainActivity.this, "Selected options menu item: Help", Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } |
That’s it! Your Android Activity should now have an options menu on the actionbar
My resources for adding my options menu to Activity
Adding the App Bar
Android SDK: Implement an Options Menu