且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建RecyclerView上下文菜单

更新时间:2023-12-06 09:36:04

  

您好,大家好,   你不能直接实现这些方法,例如 onClickListener    OnContextMenuListener 等,因为 RecycleView 扩展 android.view.ViewGroup   因此我们不能直接使用这些方法。   我们可以实现在 ViewHolder 适配器类这些方法。   我们可以使用右键菜单中RecycleView像这样

 公共静态类ViewHolder扩展RecyclerView.ViewHolder实现OnCreateContextMenuListener {
TextView的tvTitle;
ImageView的ivImage;
    公共ViewHolder(视图v){
        超级(五);
        tvTitle =(TextView中)v.findViewById(R.id.item_title);
        v.setOnCreateContextMenuListener(本);


    }
 

现在我们按照相同的步骤,同时实现了上下文菜单。

  @覆盖
    公共无效onCreateContextMenu(文本菜单菜单,视图V,
            ContextMenuInfo menuInfo){

        menu.setHeaderTitle(选择操作);
        menu.add(0,v.getId(),0,呼叫); //的groupId,的itemId,秩序,标题
        menu.add(0,v.getId(),0,SMS);

    }
 

如果你得到任何困难,请在评论。骄傲是一个androidian:)

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?

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 :)