首页 > 解决方案 > setOnCreateContextMenuListener 在 RecycleView OnBindViewHolder 中不起作用

问题描述

我正在使用setOnCreateContextMenuListenerin ,但在使用inonBindViewHolder时不会触发上下文菜单侦听器。setOnLongClickListeneronBindViewHolder

override fun onBindViewHolder(holder: friendsAdapter.ListViewHolder, position: Int) {    
        holder.tvUsername.text = listFriends[position].username
        holder.tvEmail.text = listFriends[position].email        
        mBundle = Bundle()

        holder.itemView.setOnClickListener{
            mBundle.putString(friendProfile.EXTRA_ID, listFriends[position].id)
            mBundle.putString(friendProfile.EXTRA_USERNAME, listFriends[position].username)
            mBundle.putString(friendProfile.EXTRA_EMAIL, listFriends[position].email)
            mBundle.putString(friendProfile.EXTRA_IMAGE, listFriends[position].profilelink)
            profileFrag.profileData = mBundle
            fManager
                .beginTransaction()
                .replace(R.id.nav_host_fragment, profileFrag, friendProfile::class.java.simpleName)
                .addToBackStack(null)
                .commit()
        }

        holder.itemView.setOnLongClickListener{
            Toast.makeText(context, listFriends[position].id, Toast.LENGTH_SHORT).show()
            mBundle.putString(friendProfile.EXTRA_ID, listFriends[position].id)
            profileFrag.profileData = mBundle
            return@setOnLongClickListener true
        }

        holder.itemView.setOnCreateContextMenuListener(this)
    }

标签: androidkotlinandroid-recyclerview

解决方案


定义的注释public interface OnLongClickListener告诉我们:

@return true if the callback consumed the long click, false otherwise.

因此,在您的代码中,当return@setOnLongClickListener true执行时,它会告诉侦听器该操作已被使用,而不是对其执行任何其他操作。因此,如果您总是想在这种情况下显示上下文菜单(无论如何它们都使用长按),您可以在此处输入 false (我认为)或者可能结合这两种方法,使用如下匿名方法:

                holder.itemView.setOnCreateContextMenuListener { menu, v, menuInfo ->
                Toast.makeText(context, listFriends[position].id, Toast.LENGTH_SHORT).show()
                mBundle.putString(friendProfile.EXTRA_ID, listFriends[position].id)
                profileFrag.profileData = mBundle

                // Anything else you want to do here, i.e. add menu items like this:
                menu?.add("Action")?.setOnMenuItemClickListener {
                    // Perform action when this menu item is clicked
                    true // Indicates when the user clicks this item that we don't want to do anything else with the menu
                }
                menu?.add("Another action")?.setOnMenuItemClickListener {
                    // Do something else here
                    true
                }
            }

使用此方法,您无需为上下文菜单提供菜单资源或在OnCreateContextMenuListener任何地方实现。


推荐阅读