Popup Menu Android

To display the menu below the anchor text or above the anchor text (in case the space is not available above), the Android Popup Menu is used. On clicking outside the popup menu, the menu disappears. The java.lang.Object class has the android.widget.PopupMenu as a direct subclass.

Android Popup Menu Example:

In the below example, we will demonstrate the way to create a popup menu in android.


In the activity_main.xml file, we will add only one button.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:tools = "http://schemas.android.com/tools"
    android:id = "@+id/rootview"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:orientation = "vertical"
    android:background = "#c1c1c1"
    android:gravity = "center_horizontal"
    tools:context = ".MainActivity">
        android:id = "@+id/popup"
        android:text = "Download"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content" />


The popup_menu that contains the items is created inside the res/menu directory.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
        android:id = "@+id/a"
        android:title = "A" />
        android:id = "@+id/b"
        android:title = "B"/>
        android:id = "@+id/c"
        android:title = "C"/>

Activity class:(File: MainActivity.java)

In the MainActivity.java file, we will write the code to display the popup menu on button click.

package com.example.radioapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 popupButton;
    protected void onCreate(Bundle savedInstanceState) {
        popupButton = findViewById(R.id.popup);
        popupButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
    private void popupMenuExample() {
        PopupMenu p = new PopupMenu(MainActivity.this, popupButton);
        p.getMenuInflater().inflate(R.menu.popup_menu, p .getMenu());
        p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(MainActivity.this,item.getTitle(), Toast.LENGTH_SHORT).show();
                return true;

Output 1:

Output 2:

Please follow and like us:
Content Protection by DMCA.com