Display Popup Menu On Long Press of a View in Android
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.
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:
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.
So, our app is ready. And we can see the output.
Please Login to comment...