Binoy Babu Binoy Babu - 4 months ago 1166
Android Question

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?

Answer

hello guys, 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. Proud to be an androidian :)