Android popup menu


Download Android popup menu sample

Android Popup Menu displays a Menu in a modal popup window anchored to a View. The popup will appear below the anchor view if there is room, or above it if there is not. If the IME is visible the popup will not overlap it until it is touched. Touching outside of the popup will dismiss it.

Android popup menu Android popup menu


How to add an Android popup menu?


Here is a simple way to create a popup menu:

  • Define your menu in xml
  • Instantiate a PopupMenu with its constructor, which takes the current application Context and the View to which the menu should be anchored.
  • Use MenuInflater to inflate your menu resource into the Menu object returned by PopupMenu.getMenu().
  • Call PopupMenu.show().


How to handle click event of a popup menu item?


To perform an action when the user selects a menu item, you must implement the PopupMenu.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.

Example of android popup menu


Step 1: Create a new project in Android Studio and name it Android popup Menu.

Step 2: Create a folder menu inside res directory if it is not already present.

Step 3: Open res -> menu and add a new menu resource file with a name popup_menu.xml. Now, replace the code of popup_menu.xml with the below given code.

popup_menu.xml

Step 4: Open MainActivity.java and replace its code with below given code.

MainActivity.java

Step 5: Open res -> layout -> activity_main.xml and replace its code with the below given code.

activity_main.xml

Step 6:Clean and run your project to see the result.

Share & Like

Tutorial topics

About ApnaTutorials.com

ApnaTutorials.com is for Java, J2ee, Html5 and android developers. All tutorials are well explained and are easy to understand. We have tested every tutorials on our developement environment before posting it in public domain.