The Wayback Machine - https://web.archive.org/web/20240622154537/https://www.geeksforgeeks.org/display-popup-menu-on-long-press-of-a-view-in-android/
Open In App

Display Popup Menu On Long Press of a View in Android

Last Updated : 29 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Android Popup Menu displays a list of items in a vertical list which presents the view that invoked the menu and is useful to provide an overflow of actions that are related to specific content. In this tutorial, we will learn how to display a popup menu on the long-press of a view. We will learn it by making a project in android studio. Here we will be using Kotlin as the language for development. With the help of the menu, users can experience smooth and consistent experiences throughout the application. So to enhance the UI of the app, we use a popup menu on the long press of the view. It can be any view like ImageView, EditText, TextView, etc. For this project, we will be using an ImageView. When we long press on the Image, a popup menu will display a pop-up menu.

Step by Step Implementation

Step 1: Create a New Project.

To create a new project in Android Studio please refer to Create a new project in android studio in kotlin.

Step 2: Add a vector asset in the drawable to use it as an image view  

To add a vector asset go to:

app > res > drawable > new( right-click) > vector asset

Step 3: Working with the activity_main.xml file.

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <ImageView
        android:id="@+id/img"
        android:layout_width="180dp"
        android:layout_height="180dp"
        android:src="@drawable/ic_image_24"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>


Step 4: Working with the popup_menu.xml file.

Create a menu directory and then add a new resource file in the menu for the popup menu. To create a menu in Android Studio please refer to this article. Here we need to add the item that we need to show in the menu. We need to specify there’s id and title. We can also add images along with the title. Here is the code for popup_menu.xml:

XML




<?xml version="1.0" encoding="utf-8"?>
<item
    android:id="@+id/share"
    android:title="SHARE"/>
<item
    android:id="@+id/save"
    android:title="SAVE"/>
<item
    android:id="@+id/download"
    android:title="DOWNLOAD"/>
</menu>


Step 5: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code.

Kotlin




package com.ayush.popupmenu
 
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.Toast
import java.lang.Exception
 
class MainActivity : AppCompatActivity() {
    lateinit var img: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        img = findViewById(R.id.img)
        popupMenu()
    }
 
    private fun popupMenu() {
        // creating a object of Popupmenu
        val popupMenu = PopupMenu(this, img)
 
        // we need to inflate the object
        // with popup_menu.xml file
        popupMenu.inflate(R.menu.popup_menu)
 
        // adding click listener to image
        popupMenu.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.share -> {
                    Toast.makeText(this, "Shared", Toast.LENGTH_SHORT).show()
                    true
                }
                R.id.save -> {
                    Toast.makeText(this, "saved", Toast.LENGTH_SHORT).show()
                    true
                }
                R.id.download -> {
                    Toast.makeText(this, "downloaded", Toast.LENGTH_SHORT).show()
                    true
                }
                else -> {
                    true
                }
            }
 
        }
         
        // event on long press on image
        img.setOnLongClickListener {
            try {
                val popup = PopupMenu::class.java.getDeclaredField("mPopup")
                popup.isAccessible = true
                val menu = popup.get(popupMenu)
                menu.javaClass.getDeclaredMethod("setForceShowIcon", Boolean::class.java)
                    .invoke(menu,true)
            }
            catch (e: Exception)
            {
                Log.d("error", e.toString())
            }
            finally {
                popupMenu.show()
            }
            true
        }
    }
}


So, our app is ready. And we can see the output.

Output:



Similar Reads

How to Detect Long Press on ListView Items in Android?
ListView in Android is a ViewGroup that is used to display items in rows and has an adapter that inserts the desired elements into the list. Once the items are inserted into the ListView, they can be clicked and the desired action can be performed. As multiple operations can be performed on a ListView, in this article, we will show you how you coul
3 min read
How to Detect Long Press in Android?
A Long Press refers to pressing a physical button or tap a virtual button on a touchscreen and holding it down for a second or two. Employed on touchscreens, smartphones, tablets, and smartwatches, the long press or long tap increases the user interface's flexibility. The typical "short press" or "short tap" performs one operation, while pressing/t
4 min read
Popup Menu in Android With Example
In android, the 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 androi
5 min read
Android Jetpack Compose - Display Popup Message using Alerter
In many applications, we get to see that app displays the notification when it is running on the top app bar. In this article, we will take a look at How to implement that alert notification in android applications using the Alerter library using Jetpack Compose. We will be building a simple application and displaying a button in it. On clicking on
4 min read
How to Implement Press Back Again to Exit in Android?
The 'Back' button has many different uses in many different android apps. While some app developers use it to close their apps, some use it to traverse back to the app's previous activity. Many apps require the user to press the 'Back' button two times within an interval to successfully close the application, which is considered the best practice.
2 min read
How to Disable Back Press Button in Android?
Physical keys on Android let users lock the phone, switch off the device, control volume, go back, go home and display background applications. Between all the keys, the back button is used the most in applications for navigating between activities. However, if the navigation stage reaches the start point on the continuous back press, the applicati
2 min read
How to Implement Press Back Again to Exit in Android using Jetpack Compose?
The back button is used in many android applications. It is generally used to navigate to the previous page or simply exit the application. Many applications nowadays ask users to press the back button twice to exit the application. In this article, we will be building a simple application in which we will implement press back again to exit the and
4 min read
How to Create Menu Folder &amp; Menu File in Android Studio?
Menus are the common user interface component in almost all the application. This interface provides a few options from which the user can select an option. There are 3 types of menu types available in Android: Options menu and app barContext menu and contextual action modePopup menuHow to define Menu in XML? In android, we can build the menu on ou
3 min read
Popup Window in Android using Jetpack Compose
Pop Up Window is seen in most of the applications to show the pop-up messages within the applications to the user. These pop-ups are used to display an offer image, alerts, and other important information within the android application. In this article, we will take a look at How to implement Pop Up Window in Android applications using Jetpack Comp
5 min read
How to PopUp DatePicker While Clicking on EditText in Android?
In android applications date pickers are used to pick the date from the calendars and display them within our text view. Many times we have to display this date picker dialog box by clicking on edit text and then we have to display that date within our edit text. In this article, we will take a look at How to Pop Up a Date Picker Dialog in the andr
4 min read