0

I'm working on a notepad app, and I'm having trouble with the context menus. The app has files/folders, so I have two separate context menus (one for files, one for folders). I got the menu to show for the right items by overriding the long-click listener, but it doesn't appear directly over the item; it appears like a dialog:

enter image description here

Here's the code for the long-click listener; I really feel like the problem is here; if not, I can post a little more:

override fun onItemLongClick(adapterView: AdapterView<*>?, p1: View?, pos: Int, p3: Long): Boolean {
    val p : Int = adapterView?.getItemAtPosition(pos) as Int
    currentFile = fileContents[p]
    fileList.showContextMenu()
    return true
}
Zoe
  • 27,060
  • 21
  • 118
  • 148

3 Answers3

0

You should provide the coordinates if you want to show the menu over the item. instead of fileList.showContextMenu(), use p1.showContextMenu(p1.pivotX,p1.pivotY)

    override fun onItemLongClick(adapterView: AdapterView<*>?, p1: View?, pos: Int, p3: Long): Boolean {
        val p : Int = adapterView?.getItemAtPosition(pos) as Int
        currentFile = fileContents[p]
        p1.showContextMenu(p1.pivotX,p1.pivotY)
        return true
    }
0

Ok, so I figured it out; the credit partially goes to the answer above and to this answer: OnClickListener - x,y location of event?

Basically, you implement the onTouch listener to get the last x and y coordinates and then pass them in to the showContextMenu method. Here's the code I used to implement this:

override fun onTouch(p0: View?, event: MotionEvent?): Boolean {
    if (event!!.actionMasked == MotionEvent.ACTION_DOWN) {
        lastX = event.x
        lastY = event.y
    }

    return false
}
0

I think you can get the result which you want using PopupMenu.

Here's the documentation: https://developer.android.com/reference/android/widget/PopupMenu

Here's the demo: https://play.google.com/store/apps/details?id=com.alphae.rishi.towatch I have inflated PopupMenu whenever the user clicks on the three-dot menu.