如何为 RecyclerView 创建上下文菜单 [英] How to create context menu for RecyclerView

查看:31
本文介绍了如何为 RecyclerView 创建上下文菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何为 RecyclerView 实现上下文菜单? 显然调用 registerForContextMenu(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?

推荐答案

不能像onClickListener那样直接实现这些方法,OnContextMenuListener 等,因为 RecycleView 扩展了 android.view.ViewGroup.所以我们不能直接使用这些方法.我们可以在 ViewHolder 适配器类中实现这些方法.我们可以像这样在 RecycleView 中使用上下文菜单:

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.

这篇关于如何为 RecyclerView 创建上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆