我正在尝试在回收者视图中添加上下文菜单,但是它不起作用。
在我的适配器中,我添加了以下内容

  public class ViewHolder extends RecyclerView.ViewHolder implements
   View.OnCreateContextMenuListener {
    TextView mTitle, mDescription;

    public ViewHolder(View itemView) {
        super(itemView);
        mTitle = itemView.findViewById(R.id.textViewTitle);
        mDescription = itemView.findViewById(R.id.textViewDescription);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                String title = mTitle.getText().toString();
                String descrpition = mDescription.getText().toString();
                if (mClickListener!=null)
                    mClickListener.onItemClick(v, position, title, descrpition);
            }
        });
        itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                int position = getAdapterPosition();
                if (onRecyclerViewLongClickListner!=null)
                    onRecyclerViewLongClickListner.onItemLongClick(position);
                return true;
            }
        });
        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select options");
        menu.add(0,v.getId(),0,"Option1");
    }
}


在mainActivity中,我添加了registerForContextMenu(recyclerView);

最佳答案

问题出在您的OnLongClickListener上。当您返回true时,它会消耗大量点击事件。

onLongClick方法文档中:


  如果回调消耗了长按,则为true,否则为false。


由于需要在onLongClick中创建ContextMenu,因此必须从false返回OnLongClickListener,以便系统可以创建ContextMenu

更新您的OnLongClickListener

  itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            int position = getAdapterPosition();
            if (onRecyclerViewLongClickListner!=null)
                onRecyclerViewLongClickListner.onItemLongClick(position);
              return false;
        }
    });

10-07 15:57