我的RecyclerView ContextMenu不显示

时间:2018-06-28 04:45:22

标签: android android-recyclerview android-contextmenu

我在哪里弄错了? 我的上下文菜单没有显示,我已经将setOnCreateContextMenuListenerOnCreateContextMenu移到了ViewHolder的内部,但仍然没有显示。

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
    ImageView imageview;
    TextView textView;

    public ViewHolder(View itemView) {
        super(itemView);
        imageview = itemView.findViewById(R.id.thumbImage);
        textView = itemView.findViewById(R.id.tv_imageName);
        itemView.setOnCreateContextMenuListener(getActivity());
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        String id = fArray.get(info.position).substring(fArray.get(info.position).lastIndexOf("/")+1).replace(".jpg", "");
        if (v.getId()==R.id.gridView1) {
            menu.setHeaderTitle(id);
            EditName = id;
            String[] menuItems = {"Edit"};

            for (int i = 0; i<menuItems.length; i++) {
                menu.add(Menu.NONE, i, i, menuItems[i]);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

 public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
      ImageView imageview;
      TextView textView;
        public ViewHolder(View itemView) {
            super(itemView);
            imageview = itemView.findViewById(R.id.thumbImage);
            textView = itemView.findViewById(R.id.tv_imageName);
            itemView.setOnCreateContextMenuListener(this);

        }


        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            MenuItem star=menu.add(Menu.NONE,1,1,"Star");
            MenuItem edit=menu.add(Menu.NONE,2,2,"Edit");
            MenuItem delete=menu.add(Menu.NONE,3,3,"Delete");
            star.setOnMenuItemClickListener(this);
            edit.setOnMenuItemClickListener(this);
            delete.setOnMenuItemClickListener(this);
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            int s1=list.get(getAdapterPosition()).getId();
            switch (item.getItemId()){
                case 1:
                    Toast.makeText(context, "pressed on star", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(context, "pressed on edit", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(context, "pressed on edit", Toast.LENGTH_SHORT).show();
                    break;

            }
            return true;
        }
    }

希望这会对您有所帮助。