Tuesday, 2 November 2021

LongClick on subMenu item of overflow menu

I'm working on the project that has an overflow menu in the android app. in onCreateOptionsMenu() I dynamically update the menu and a submenu based on user details but the task requires me to have 2 actions with that menu button, I already have a single click via onOptionsItemSelected()

is it possible to add something like OnLongClickListener to an item of the sub-menu for the overflow menu?

In my menu XML I set the subItem like this

<item
android:id="@+id/help"
android:orderInCategory="101"
android:title="Help"
app:actionViewClass="android.widget.ImageButton"
app:showAsAction="never" >
<menu xmlns:android="http://schemas.android.com/apk/res/android"        xmlns:HTMLCode="http://schemas.android.com/apk/res-auto" >
    <item android:id="@+id/event1"
        android:title="Event 1"
        app:actionViewClass="android.widget.TextView"
        HTMLCode:showAsAction="ifRoom|withText" />
    <item android:id="@+id/event2"
        android:title="Event 2"
        app:actionViewClass="android.widget.TextView"
        HTMLCode:showAsAction="ifRoom|withText" />
    <item android:id="@+id/event3"
        android:title="Event 3"
        app:actionViewClass="android.widget.TextView"
        HTMLCode:showAsAction="ifRoom|withText" />
</menu>

then in the on onCreateOptionsMenu i attach longClick like this

    var helpMenuItem = menu.findItem(R.id.help)
helpMenuItem.subMenu?.let { subMenu ->
    val ct = subMenu.size()
    for (i in 0 until ct) {
        val subItem = subMenu.getItem(i)
        subItem.actionView?.let { view ->
            view.setOnLongClickListener {
                Log.d("Long Click Event", "I'm here!!")
                true
            }
        }
    }
}

The code compiles but I was never able to get onLongClick. Please help have been looking for the solution for a few days wo luck



from LongClick on subMenu item of overflow menu

No comments:

Post a Comment