How to create context menu for RecyclerView

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

    In my case I had to use data from my fragment in the onContextItemSelected() method. The solution I ended up going with was to pass an instance of the fragment into my adapter and register the view item in the view holder:

    @Override
    public void onBindViewHolder(final MyListAdapter.ViewHolder viewHolder, int position) {
        final Object rowObject = myListItems.get(position);
    
        // Do your data binding here
    
        viewHolder.itemView.setTag(position);
        fragment.registerForContextMenu(viewHolder.itemView);
    }
    

    Then in onCreateContextMenu() you can save the index to a local variable:

    selectedViewIndex = (int)v.getTag();

    and retrieve it in onContextItemSelected()

提交回复
热议问题