Search code examples
androidcontextmenuandroid-recyclerview

How to create context menu for RecyclerView


How do I implement context menu for RecyclerView? Apparently calling registerForContextMenu(recyclerView) doesn't work. I'm calling it from a fragment. Did anybody have any success implementing this?


Solution

  • You can't directly implement these method like onClickListener, OnContextMenuListener etc. because RecycleView extends android.view.ViewGroup. So we cant directly use these method. We can implement these methods in ViewHolder adapter class. We can use context menu in RecycleView like this way:

    public static class ViewHolder extends RecyclerView.ViewHolder implements OnCreateContextMenuListener {
        
        TextView tvTitle;
        ImageView ivImage;
        
        public ViewHolder(View v) {
            super(v);
            tvTitle =(TextView)v.findViewById(R.id.item_title);
            v.setOnCreateContextMenuListener(this);
            
            
        }
    }
    

    Now we follow the same procedure while implements the context menu.

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
         
        menu.setHeaderTitle("Select The Action");    
        menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title   
        menu.add(0, v.getId(), 0, "SMS"); 
        
    }
    

    If you get any difficulties ask in comment.