我在setOnCreateContextMenuListener中使用onBindViewHolder,但是当我在setOnLongClickListener中使用onBindViewHolder时,不会触发上下文菜单侦听器。

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) 
    } 

请您参考如下方法:

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。


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!