Figure 4. A popup menu in the Gmail app, anchored to the overflow
button at the top-right.
Creating a Popup Menu
APopupMenu
is a modal menu anchored to a View
.
It appears below the anchor view if there is room, or above the view otherwise. It's useful for:- Providing an overflow-style menu for actions that relate to specific content (such as
Gmail's email headers, shown in figure 4).
Note: This is not the same as a context menu, which is generally for actions that affect selected content. For actions that affect selected content, use the contextual action mode or floating context menu.
- Providing a second part of a command sentence (such as a button marked "Add" that produces a popup menu with different "Add" options).
- Providing a drop-down similar to
Spinner
that does not retain a persistent selection.
Note:
If you define your menu in XML, here's how you can show the popup menu:PopupMenu
is available with API
level 11 and higher.- Instantate a
PopupMenu
with its constructor, which takes the current applicationContext
and theView
to which the menu should be anchored. - Use
MenuInflater
to inflate your menu resource into theMenu
object returned byPopupMenu.getMenu()
. On API level 14 and above, you can usePopupMenu.inflate()
instead. - Call
PopupMenu.show()
.
android:onClick
attribute
that shows a popup menu:<ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_overflow_holo_dark" android:contentDescription="@string/descr_overflow_button" android:onClick="showPopup" />The activity can then show the popup menu like this:
public void showPopup(View v) { PopupMenu popup = new PopupMenu(this, v); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.actions, popup.getMenu()); popup.show(); }In API level 14 and higher, you can combine the two lines that inflate the menu with
PopupMenu.inflate()
.The menu is dismissed when the user selects an item or touches outside the menu area. You can listen for the dismiss event using
PopupMenu.OnDismissListener
.Handling click events
To perform an action when the user selects a menu item, you must implement thePopupMenu.OnMenuItemClickListener
interface and register it with your PopupMenu
by calling setOnMenuItemclickListener()
. When the user selects an item, the system calls the onMenuItemClick()
callback in
your interface.For example:
public void showMenu(View v) { PopupMenu popup = new PopupMenu(this, v); // This activity implements OnMenuItemClickListener popup.setOnMenuItemClickListener(this); popup.inflate(R.menu.actions); popup.show(); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.archive: archive(item); return true; case R.id.delete: delete(item); return true; default: return false; } }
More Details: http://developer.android.com/guide/topics/ui/menus.html
0 comments
Thanks for your comment