How to create context menu for RecyclerView

后端 未结 21 2656
日久生厌
日久生厌 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 01:54

    I've been struggling on this because Android does not handle this nicely for me in RecyclerView, which was working very well for ListView.

    The most difficult piece is that the ContextMenuInfo piece is embedded inside a View, which you can't easily attach other than overriding the View.

    So you will need a wrapper that helps you deliver the position info to the Activity.

    public class RecyclerContextMenuInfoWrapperView extends FrameLayout {
    private RecyclerView.ViewHolder mHolder;
    private final View mView;
    
    public RecyclerContextMenuInfoWrapperView(View view) {
        super(view.getContext());
        setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mView = view;
        addView(mView);
    }
    
    public void setHolder(RecyclerView.ViewHolder holder) {
        mHolder = holder;
    }
    
    @Override
    protected ContextMenu.ContextMenuInfo getContextMenuInfo() {
        return new RecyclerContextMenuInfo(mHolder.getPosition(), mHolder.getItemId());
    }
    
    public static class RecyclerContextMenuInfo implements ContextMenu.ContextMenuInfo {
    
        public RecyclerContextMenuInfo(int position, long id) {
            this.position = position;
            this.id = id;
        }
    
        final public int position;
        final public long id;
    }
    

    }

    Then in your RecyclerAdapter, when you create ViewHolders, you need to set the Wrapper as the root view, and register contextMenu on each view.

    public static class AdapterViewHolder extends RecyclerView.ViewHolder {
        public AdapterViewHolder(  View originalView) {
            super(new RecyclerContextMenuInfoWrapperView(originalView);
            ((RecyclerContextMenuInfoWrapperView)itemView).setHolder(this);
            yourActivity.registerForContextMenu(itemView);
            itemView.setOnCreateContextMenuListener(yourListener);
        }
    

    }

    And lastly, in your Activity, you'll be able to do what you usually do:

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        int position = ((RecyclerContextMenuInfoWrapperView.RecyclerContextMenuInfo)item.getMenuInfo()).position;
        // do whatever you need as now you have access to position and id and everything
    

提交回复
热议问题