Reputation: 12010
I have added a menu item in an android application.
Here is the code:
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(1, 1, 0, "Item 1");
return true;
}
I need to show an alert dialog when user clicks the menu item.
My code for alert dialog
final Activity activity = this;
AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setTitle("Item 1");
alertDialog.setMessage("This is Item 1");
alertDialog.show();
Upvotes: 1
Views: 375
Reputation: 133560
Override onOptionsItemSelected
. Your item id is 1. use switch case and show the diloag.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
AlertDialog alertDialog = new AlertDialog.Builder(ActivityName.this).create(); // You can use activity context directly.
alertDialog.setTitle("Item 1");
alertDialog.setMessage("This is Item 1");
alertDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public abstract MenuItem add (int groupId, int itemId, int order, CharSequence title)
Added in API level 1 Add a new item to the menu. This item displays the given title for its label.
Parameters
groupId The group identifier that this item should be part of. This can be used to define groups of items for batch state changes. Normally use NONE if an item should not be in a group.
itemId Unique item ID. Use NONE if you do not need a unique ID. order The order for the item. Use NONE if you do not care about the order. See getOrder().
title The text to display for the item.
Returns
The newly added menu item.
public boolean onOptionsItemSelected (MenuItem item)
Added in API level 1
This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.
Derived classes should call through to the base class for it to perform the default menu handling.
Parameters item The menu item that was selected.
Returns
boolean Return false to allow normal menu processing to proceed, true to consume it here.
Upvotes: 1