I am using setOnCreateContextMenuListener in onBindViewHolder, but the context menu listener is not triggered when I using setOnLongClickListener in the 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)
}
The comment for the definition for
public interface OnLongClickListenertells us:so in your code, when
return@setOnLongClickListener trueexecutes, it tells the listener that the action has been consumed, and not to do anything else with it. So you can put false here (I think) or potentially combine those two methods if you always want to show the context menu in this case (they both use the long click anyway), using an anonymous method like this:With this method you don't need to have menu resources for the context menu or to implement
OnCreateContextMenuListeneranywhere.