How to create context menu for RecyclerView

后端 未结 21 2664
日久生厌
日久生厌 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:20

    The current answer is not correct. Here's a working implementation:

    public class ContextMenuRecyclerView extends RecyclerView {
    
      private RecyclerViewContextMenuInfo mContextMenuInfo;
    
      @Override
      protected ContextMenu.ContextMenuInfo getContextMenuInfo() {
        return mContextMenuInfo;
      }
    
      @Override
      public boolean showContextMenuForChild(View originalView) {
        final int longPressPosition = getChildPosition(originalView);
        if (longPressPosition >= 0) {
            final long longPressId = getAdapter().getItemId(longPressPosition);
            mContextMenuInfo = new RecyclerViewContextMenuInfo(longPressPosition, longPressId);
            return super.showContextMenuForChild(originalView);
        }
        return false;
      }
    
      public static class RecyclerViewContextMenuInfo implements ContextMenu.ContextMenuInfo {
    
        public RecyclerViewContextMenuInfo(int position, long id) {
            this.position = position;
            this.id = id;
        }
    
        final public int position;
        final public long id;
      }
    }
    

    In your Fragment (or Activity):

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecyclerView = view.findViewById(R.id.recyclerview);
        registerForContextMenu(mRecyclerView);
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        // inflate menu
        MenuInflater inflater = getActivity().getMenuInflater();
        inflater.inflate(R.menu.my_context_menu, menu);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        return super.onContextItemSelected(item);
        RecyclerViewContextMenuInfo info = (RecyclerViewContextMenuInfo) item.getMenuInfo();
        // handle menu item here
    }
    

    And finally, in your ViewHolder:

    class MyViewHolder extends RecyclerView.View.ViewHolder {
        ...
        private void onLongClick() {
            itemView.showContextMenu();
        }
    }
    

提交回复
热议问题