Popup Menu in Android With Example

26 Nov, 2020
In android, Menu is an important part of the UI component which is used to provide some common functionality around the application. With the help of the menu, users can experience smooth and consistent experiences throughout the application. In android, we have three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are the following:
Android Options Menu: Android Options Menu is a primary collection of menu items in an android application and useful for actions that have a global impact on the searching application.
Android Context Menu: Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and useful for elements that affect the selected content or context frame.
Android Popup Menu: Android Popup Menu displays a list of items in a vertical list which presents to the view that invoked the menu and useful to provide an overflow of actions that related to specific content.
So in this article, we are going to discuss the Popup Menu. A PopupMenu displays a Menu in a popup window anchored to a View. The popup will be shown below the anchored View if there is room(space) otherwise above the View. If any IME(Input Method Editor) is visible the popup will not overlap it until the View(to which the popup is anchored) is touched. Touching outside the popup window will dismiss it.
In this example, we are going to make a popup menu anchored to a Button and on click, the popup menu will appear, and on a touch of the popup menu item, a Toast message will be shown. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
In this step, we will add a button to the layout file and give it an id as clickBtn to it.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <Button        android:id="@+id/clickBtn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="#0F9D58"        android:text="Click Me"        android:textColor="#ffffff"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout>
Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. 
XML
<resources>    <color name="colorPrimary">#0F9D58</color>    <color name="colorPrimaryDark">#16E37F</color>    <color name="colorAccent">#03DAC5</color></resources>
Step 3: Creating menu directory and menu file
First, we will create a menu director which will contain the menu file. Go to app > res > right-click > New > Android Resource Directory and give Directory name and Resource type as menu.
Now, we will create a popup_menu file inside that menu resource directory. Go to app > res > menu > right-click > New > Menu Resource File and create a menu resource file and name it as popup_menu. In the popup_menu file, we will add menu items. Below is the code snippet for the popup_menu.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android">      <item        android:id="@+id/java"        android:title="Java" />      <item        android:id="@+id/kotlin"        android:title="Kotlin" />      <item        android:id="@+id/android"        android:title="Android" />      <item        android:id="@+id/react_native"        android:title="React Native" />  </menu>
Step 4: Working with the MainActivity.java file
In the MainActivity.java file, we will get the reference of the Button and initialize it. Add onClick behavior to the button and inflate the popup menu to it. Below is the code snippet for the MainActivity.java file.
Java
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.PopupMenu;import android.widget.Toast;  public class MainActivity extends AppCompatActivity {      Button button;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // Referencing and Initializing the button        button = (Button) findViewById(R.id.clickBtn);                    // Setting onClick behavior to the button        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                // Initializing the popup menu and giving the reference as current context                PopupMenu popupMenu = new PopupMenu(MainActivity.this, button);                                    // Inflating popup menu from popup_menu.xml file                popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {                    @Override                    public boolean onMenuItemClick(MenuItem menuItem) {                        // Toast message on menu item clicked                        Toast.makeText(MainActivity.this, "You Clicked " + menuItem.getTitle(), Toast.LENGTH_SHORT).show();                        return true;                    }                });                // Showing the popup menu                popupMenu.show();            }        });    }}
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.