如何在LungClickListener上设置recyclerview项时具有ContextMenu

时间:2016-09-20 17:40:40

标签: android android-recyclerview contextmenu

如果在onLongClickListener上设置视图,如何在RecyclerViewAdapter中设置上下文菜单?

这是我的代码:

 public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

            public TextView name;

            public ViewHolder(View itemLayoutView) {

                super(itemLayoutView);
                name = (TextView) itemLayoutView.findViewById(R.id.rvname);

                itemLayoutView.setOnClickListener(this);
                itemLayoutView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        return false;
                    }

                });
            }

以下是我想要实现的示例图像

enter image description here

2 个答案:

答案 0 :(得分:5)

根据我的经验,我不需要setOnLongClickListener来显示上下文菜单,View.OnCreateContextMenuListener会为我做这些。

这是我的工作代码:

public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener {

    public TextView name;

    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        name = (TextView) itemLayoutView.findViewById(R.id.rvname);
        itemLayoutView.setOnClickListener(this);
        itemLayoutView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onClick(View v) {
        String location = name.getText().toString();
        Intent goFlip = new Intent(RecyclerAdapter.context, FlipActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("name", location);
        bundle.putInt("pos", getAdapterPosition());
        goFlip.putExtras(bundle);
        context.startActivity(goFlip);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select Action");
        MenuItem edit = menu.add(Menu.NONE,1,1,"Edit");
        MenuItem delete = menu.add(Menu.NONE,2,2,"Delete");


        edit.setOnMenuItemClickListener(onChange);
        delete.setOnMenuItemClickListener(onChange);
    }
    private final MenuItem.OnMenuItemClickListener onChange = new MenuItem.OnMenuItemClickListener() {
       @Override
       public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()){
                case 1:
                    Toast.makeText(context,"Edit",Toast.LENGTH_LONG).show();
                    return true;
                case 2:
                    Toast.makeText(context,"Delete",Toast.LENGTH_LONG).show();
                    return true;
            }
           return false;
       }
   };
}

我还想分享我发现的链接: https://gist.github.com/gauravat16/e8e03496a4056829e65dede3c236da28

答案 1 :(得分:1)

您需要实施PopupMenu 可以找到实施here