How to create context menu for RecyclerView

后端 未结 21 2722
日久生厌
日久生厌 2020-11-28 01:20

How do I implement context menu for RecyclerView? Apparently calling registerForContextMenu(recyclerView) doesn\'t work. I\'m calling it from a fra

21条回答
  •  青春惊慌失措
    2020-11-28 02:21

    Here's a simpler way to do it with Kotlin that worked for me. The major challenge is figuring out the position of the item that was pressed. Inside your adapter, you can place this code snippet and it'll be able to capture the position of the item for whom the context menu is shown; that's all.

    override fun onBindViewHolder(holder: YourViewHolder, position: Int) {
    
    ...     
    
        holder.view.setOnCreateContextMenuListener { contextMenu, _, _ -> 
                contextMenu.add("Add").setOnMenuItemClickListener {
                        longToast("I'm pressed for the item at position => $position")
                        true    
                }       
        }       
    
    } 
    

提交回复
热议问题