Android OptionsMenu Tutorial
Menu is
an important user interface component which provides some action options for a
particular activity. In this post I’ll show the basics for setting up a menu.
The final output will look like this:
The activity will contain 2 menu
options: Add and Help. When clicking an option menu, a Toast notification will be
displayed.
Fill in the content of options.xml file with following code:
1
2
3
4
5
6
7
8
9
10
11
12
|
<?xml version="1.0" encoding="utf-8"?>
<item
android:id="@+id/add"
android:icon="@android:drawable/ic_menu_add"
android:title="Add"/>
<item
android:id="@+id/help"
android:icon="@android:drawable/ic_menu_help"
android:title="Help"/>
</menu>
|
menu – defines the menu
item – defines a menu item
item – defines a menu item
4. Open
the main Activity class and type following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public class MenuTestActivity
extends Activity {
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
// Inflate the menu
@Override
public boolean onCreateOptionsMenu(Menu
menu) {
MenuInflater
inflater = getMenuInflater();
inflater.inflate(R.menu.options,
menu);
return true;
}
// Handle click
events
@Override
public boolean onOptionsItemSelected(MenuItem
item) {
switch (item.getItemId())
{
case R.id.add:
Toast.makeText(this,
"Add", Toast.LENGTH_SHORT).show();
return true;
case R.id.help:
Toast.makeText(this,
"Help", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
– The onCreateOptionsMenu() method
inflates your menu defined in the XML resource.
– The onOptionsItemSelected() method
handle click events. When the user selects an item from the options menu, the
system calls the onOptionsItemSelected() method.
This method passes the MenuItemselected. The MenuItem can identify the item by
calling the getItemId() which
returns the unique ID for the menu item defined by the android:id attribute
in the menu resource. Depending of the returned ID, we display the appropriate
Toast notification.