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
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>
<?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>
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()
}
}
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):
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.