Kotlin Popup Menu (KPM)


KPM:   SOLD       




Hi guys, this time I will share my experience in creating a feature known as a popup menu, which will display simple options when the dot extra option is clicked.

Android Popup Menu is a list of menus that appear vertically onto the display. The popup menu appears below the display if there is space otherwise it appears above. Touching outside the popup menu makes it disappear.

Popup Menus provide actions related to specific content, and do not affect related content.

The PopupMenu.OnMenuItemClickListener interface receives click events of a menu item if the item does not have a click listener.

1. Create a Resource Menu

Add by right clicking -> new -> android resource file -> resource type (select menu)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/opt_edit"
        android:background="?android:attr/selectableItemBackground"
        android:title="@string/edit" />
    <item
        android:id="@+id/opt_delete"
        android:background="?android:attr/selectableItemBackground"
        android:title="@string/delete" />
</menu>

2. Pin Menu and Display

Embed the menu resource into the Popup Menu component and then display it.

            val opt = PopupMenu(context, itemBinding.option)
            opt.inflate(R.menu.plan_option)
            opt.setOnMenuItemClickListener {
                when (it.itemId) {
                    R.id.opt_edit -> onClick(ON_EDIT)
                    R.id.opt_delete -> onClick(ON_DELETE)
                }
                return@setOnMenuItemClickListener true
            }

            itemBinding.option.setOnClickListener {
                opt.show()
            }

Post a Comment

Previous Next

نموذج الاتصال