Pular para o conteúdo principal

Kotlin Android PopupMenu Example

PopupMenu in Android: A Beginner's Guide

Android is a popular mobile operating system that provides a wide range of features to build interactive and user-friendly applications. One of the most useful features of Android is the PopupMenu, which allows developers to create context menus that are displayed when the user performs a long click on a view or presses a button.

In this article, we will discuss PopupMenu in Android and provide a step-by-step guide on how to create a PopupMenu in your Android application.

What is a PopupMenu?

A PopupMenu is a type of context menu that is displayed when the user performs a long click on a view or presses a button. It provides a list of options that the user can choose from to perform a specific action. PopupMenu is an efficient way to provide a lot of options in a limited space.

Creating a PopupMenu in Android

To create a PopupMenu in Android, we need to follow the below steps:

Step 1: Add a Button to your Layout

First, you need to add a Button to your layout. The Button will be used to trigger the PopupMenu.

<Button
android:id="@+id/popup_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup Menu" />

Step 2: Create a Menu Resource File

Next, we need to create a menu resource file where we define the options that will be displayed in the PopupMenu.

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_item_1"
android:title="Option 1" />
<item
android:id="@+id/menu_item_2"
android:title="Option 2" />
<item
android:id="@+id/menu_item_3"
android:title="Option 3" />
</menu>

Step 3: Inflate the Menu Resource File

Now we need to inflate the menu resource file in our Java or Kotlin code. We can do this by creating an instance of PopupMenu and passing the Button view and the menu resource file ID as arguments.

val popupButton = findViewById<Button>(R.id.popup_button)
val popupMenu = PopupMenu(this, popupButton)
popupMenu.menuInflater.inflate(R.menu.popup_menu, popupMenu.menu)

Step 4: Set a Listener to the PopupMenu

We need to set a listener to the PopupMenu to handle the user's selection. We can do this by calling setOnMenuItemClickListener() method and passing a listener that implements the OnMenuItemClickListener interface.

popupMenu.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.menu_item_1 -> {
// Action for menu item 1
true
}
R.id.menu_item_2 -> {
// Action for menu item 2
true
}
R.id.menu_item_3 -> {
// Action for menu item 3
true
}
else -> false
}
}

Step 5: Display the PopupMenu

Finally, we need to call the show() method on the PopupMenu instance to display the PopupMenu.

popupMenu.show()

Let us look at more examples.

Example 1 - Kotlin Popupmenu Example

Here is a simple popupmenu in kotlin android. Follow the following steps to create and run the example.

Step 1: Dependencies.

No special or third party dependency is needed.

Step 2: Create Menu resource file

Create a folder called menu under the res directory and in it create a file called popup_menu_button.xml

popup_menu_button.xml

In this file create a menu and in it create the menu items as follows:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
android:id="@+id/popMenu_Edit"
android:icon="@drawable/ic_edit"
android:title="Edite"/>

<item
android:id="@+id/popMenu_Delete"
android:icon="@drawable/ic_delete"
android:title="Delete"/>

<item
android:id="@+id/popMEnu_Shared"
android:icon="@drawable/ic_share"
android:title="Shared" />

</menu>

Step 3: Create XML Layout

Add a TextView and a Button inside a ConstraintLayout as follows:

activity_main.xm

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Show popup Menu"
android:textAllCaps="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 4: Create a Popup

Create a class called ShowPopupMenu.kt and add the code to instantiate the PopupMenu and inflate the menu items and listen to their click events. Here is the full code:

ShowPopupMenu.kt

import android.content.Context
import android.view.View
import android.widget.PopupMenu
import android.widget.Toast
import com.example.simple.show.popmenu.R

class ShowPopupMenu {

fun showPopMenu(context: Context, view: View) {

val pop = PopupMenu(context, view)
pop.inflate(R.menu.pop_menu_button)

pop.setOnMenuItemClickListener {
when (it!!.itemId) {
R.id.popMenu_Edit -> {
Toast.makeText(context, "item Edite", Toast.LENGTH_SHORT).show()
true
}
R.id.popMenu_Delete -> {
Toast.makeText(context, "item Delete", Toast.LENGTH_SHORT).show()
true
}
R.id.popMEnu_Shared -> {
Toast.makeText(context, "item Shared", Toast.LENGTH_SHORT).show()
true
}
else -> false

}
}

try {

val fieldMpopup = PopupMenu::class.java.getDeclaredField("mPopup")
fieldMpopup.isAccessible= true
val mPopup = fieldMpopup.get(pop)
mPopup.javaClass
.getDeclaredMethod("setFoeceShowIcon",Boolean::class.java)
.invoke(mPopup,true)

}catch (e:Exception){

}finally {
pop.show()
}

}

}

Step 5: Laucher Activity

Here is the code for the main activity:

MainActivity.kt

import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.example.simple.show.popmenu.R
import com.example.simple.show.popmenu.utility.ShowPopupMenu

class MainActivity : AppCompatActivity() {

lateinit var buttonShowPopupMenu: Button
val showPopMenu = ShowPopupMenu()

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

Cast()

buttonShowPopupMenu.setOnClickListener {
showPopMenu.showPopMenu(this, it)
}

}

private fun Cast() {
buttonShowPopupMenu = findViewById(R.id.button)
}

}

Step 6: Run

Finally run the project.

Reference

Here are the code reference links:

NumberLink
1.Download code
2.Follow code author

Conclusion

In this article, we have discussed PopupMenu in Android and provided a step-by-step guide on how to create a PopupMenu in your Android application. By following these steps, you can easily create a PopupMenu that provides a list of options for the user to choose from. PopupMenu is a powerful feature that can make your application more user-friendly and interactive.