Creating Popup Menu in Android Using Kotlin: Step-by-Step Guide

Learn how to implement a popup menu in your Android application using Kotlin. This tutorial provides a detailed, step-by-step guide on setting up a menu resource file and programmatically handling its display. Follow along to enhance your app's user interface with a versatile and interactive popup menu that improves usability and functionality.
Submitted on July 07, 2024

Create Menu Resource File

  • Right-click on the res directory in Android Studio.
  • Navigate to New -> Android Resource Directory and name it menu.
  • Inside the menu directory, create a new XML file named popup_menu.xml.

Example popup_menu.xml:


<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_edit"
        android:title="Edit" />
    <item
        android:id="@+id/action_delete"
        android:title="Delete" />
</menu>

Create the activity layout (res/layout/activity_main.xml):

  • Add a button in your layout file where you want to trigger the popup menu.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnShowPopup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Open Menu"
        android:layout_centerInParent="true" />

</RelativeLayout>

Implement the popup menu in your MainActivity (MainActivity.kt):

  • In your activity, initialize the button and handle its click event to show the popup menu.

import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.PopupMenu
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.btnShowPopup)

        button.setOnClickListener {
            showPopupMenu(button)
        }
    }

    private fun showPopupMenu(view: View) {
        val popupMenu = PopupMenu(this, view)
        popupMenu.inflate(R.menu.popup_menu)  // Menu resource file
        popupMenu.setOnMenuItemClickListener { item: MenuItem ->
            when (item.itemId) {
                R.id.action_edit -> {
                    // Handle edit click
                     showToast("Edit clicked")
                    true
                }
                R.id.action_delete -> {
                    // Handle delete click
                     showToast("Delete clicked")
                    true
                }
                else -> false
            }
        }
        popupMenu.show()
    }
    
     private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
}

Explanation:

  • Layout (activity_main.xml): This layout file should contain a button or any other view that triggers the popup menu when clicked. In this example, it uses a button with the ID buttonShowPopup.

  • Kotlin Code (MainActivity.kt):

    • showPopupMenu(): This function creates a PopupMenu and inflates the menu resource (popup_menu.xml) into it. It then sets an OnMenuItemClickListener to handle menu item clicks.
    • showToast(): A helper function to display a toast message for demonstration purposes when a menu item is clicked.

4. Integrating with UI Elements:

  • If you're using a different UI element (e.g., a TextView, ImageView) to trigger the popup menu, replace buttonShowPopup with the appropriate view ID in both the XML layout file and the Kotlin code.

5. Running the App:

  • Run the app on an emulator or physical device. Click the designated UI element (button in this example) to trigger the popup menu.

This setup provides a basic popup menu that responds to user actions with toast messages. Adjustments can be made to fit specific requirements, such as handling different menu items or performing different actions based on user selections.