Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Android Menu (OptionsMenu)


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
version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android" >
   
      android:id="@+id/add"
      android:icon="@android:drawable/ic_menu_add"
      android:title="Add"/>

   
      android:id="@+id/help"
      android:icon="@android:drawable/ic_menu_help"
      android:title="Help"/>
menu – defines the menu
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.




This post first appeared on Android Technology, please read the originial post: here

Share the post

Android Menu (OptionsMenu)

×

Subscribe to Android Technology

Get updates delivered right to your inbox!

Thank you for your subscription

×