Android PopupMenu : Show floating menu anchored to a view

PopupMenu shows floating Menu in a popup window anchored to a view. PopupMenu was added with API level 11. PopupMenu itself decides its position on screen around anchor view based upon available space. If there is room below anchor view, it will show below it. Otherwise it will be shown above anchor view.

PopupMenu provides two interfaces to handler dismiss and item click.

1. PopupMenu.OnDismissListener
Callback interface used to notify the application that popup menu has been closed.

2. PopupMenu.OnMenuItemClickListener
Interface responsible for receiving menu item click events if the items themselves do not have individual item click listeners.

Sample PopupMenu Application

PopupMenu_Bottom PopupMenu_Top

Our main target is to achieve above output. Activity layout will have two buttons one each aligned to top and bottom of view. PopupMenu will be shown on clicking buttons. In screenshot, PopupMenu is shown above it for anchor view in bottom and it is shown below anchor view for top aligned button.

Second target is to acheive styling of PopupMenu. We will define style for text appearance and background of PopupMenu as by deafult it will have style inherited from android:Widget.Holo.Light.ListPopupWindow.

Let’s start making changes with /res/layout/activity_main.xml. Final xml will be similar to as below.

We need to create a menu layout to be inflated in PopupMenu. Create /res/menu/popup_menu.xml as below.
For styling PopupMenu,add below lines to /res/values/styles.xml. It is assumed that Application theme is set to android:theme="@style/AppTheme" in manifest file.
Finally, Let add code for PopupMenu in MainActivity.java. Activity will implement View.OnClickListener for listening to onClick events for buttons. In onClick(), We will create a PopupMenu object. View will be set with inflate(int resourceId). Attach OnDismissListener and OnMenuItemClickListener in order to listen for menu dismiss and handling for menu click events.

You may also like...

  • Popup Menu in android studio
    if you are beginner and do not know how to create a popup menu in android this lecture can help you a lot
    http://themasterworld.com/popup-menu-in-android-studio/

  • Michael Lee

    Can I set the content of the popup menu without the popup_menu.xml but in the codes? How should I do? Thx!

    • here we are using PopupMenu class. You should use PopupWindow for custom views.