September 24, 2021

Show popup menu in android kotlin code

By lj

Popup menu

Popup menu is similar to menu, when you clicked on more (three dots). But this menu can be used at any position in screen. You might have seen this type of menu in recyclerview item also.

Popup menu uses anchor to show. I have used it with button, so I can assign button as anchor of it.

Create Menu

Look for res -> menu folder, if not exists add new, right click on it and create new file named menu_popup like below :

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

    <item android:title="Android" android:icon="@drawable/ic_android_black_24dp"/>
    <item android:title="IOS" android:icon="@drawable/ic_android_black_24dp" />
    <item android:title="Windows"  android:icon="@drawable/ic_android_black_24dp"/>
</menu>

Show Popup Menu

Get button in activity by findviewById or either with binding, and then in onClickListener of it use below code to show popup menu

val popupMenu = PopupMenu(this@PopupMenuExample, button)

// Inflating popup menu from popup_menu.xml file
popupMenu.getMenuInflater().inflate(R.menu.menu_popup, popupMenu.getMenu())
popupMenu.setOnMenuItemClickListener { menuItem -> // Toast message on menu item clicked
    Toast.makeText(
        this@PopupMenuExample,
        "You Clicked " + menuItem.getTitle(),
        Toast.LENGTH_SHORT
    ).show()
    true
}
// Showing the popup menu
// Showing the popup menu
popupMenu.show()

Above code create popup menu class, inflate menu layout in popup menu and show. Also specified menuitem clicks to show clicked item.

Margin for popup menu?

There might be some situation, we need to give some margin to our popup menu. To give some margin or spacing we need to create styles.xml file in res -> values (If not exists). Create style as below :

<style name="MyPopupMenu" parent="@style/Widget.AppCompat.PopupMenu">
    <item name="android:dropDownHorizontalOffset">-8dp</item>
    <item name="android:dropDownVerticalOffset">16dp</item>
</style>

Now modify our popup menu creation like as below :

val popupMenu = PopupMenu(this@PopupMenuExample, button, Gravity.END,0,R.style.MyPopupMenu)