Android pop up menu

Popup Menu

On certain user actions, the menu is displayed as a list of items within a modal popup window, this is called a popup menu. The popup menu is closely anchored to the corresponding view. The popup menu will by default appear below the corresponding view, but if there is no space below the view it can appear above as well. The popup menu is automatically closed once touched outside the popup menu. In Android, the popup menu is supported on the versions above 3.0. The following code demonstrates the popup menu.
The android Popup Menu represents the menu below the anchor text when space is available unless above the anchor text. So it goes when we click outside the popup menu. The android.widget.PopupMenu is the straight subclass of java.lang.Object class. Now, how to create a popup menu in android.

  • Using activity_main.xml: It comprises only one button, like activity_main.xml
  • popup_menu.xml: It comprises three items. It is formed inside the res/menu directory, like poupup_menu.xml
  • Activity class: It represents the popup menu on a button click, like

The Nested classes

  • The interface
  • 1. PopupMenu.OnDismissListener: A callback interface is practised to tell the application that the menu has closed.

    2. PopupMenu.OnMenuItemClickListener: This interface efficiently accepts menu item click events when the items themselves do not have specific item click listeners.

The Public constructors

  • PopupMenu(Context context, View anchor): This constructor is used to form a new popup menu along with an anchor view.
  • PopupMenu(Context context, View anchor, int gravity): It is used for forming a new popup menu with an anchor view and alignment gravity.
  • PopupMenu(Context context, View anchor, int gravity, int popupStyleAttr, int popupStyleRes): This constructor is used to form a new popup menu with a unique style.