如果没有onBindViewHolder中的锚点,则无法使用MenuPopupHelper

时间:2017-03-19 10:15:50

标签: android android-cardview android-viewholder

点击菜单图标时出现此错误:

java.lang.IllegalStateException: MenuPopupHelper cannot be used without an anchor

我有这段代码:

@Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

...

holder.imageButtom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopup(holder.imageButtom, position, post.getPid());
            }
        });

和showpopup

private void showPopup(View view, final int position, final String id) {
    View menuItemView = view.findViewById(R.id.card_view);
    PopupMenu popup = new PopupMenu(context, menuItemView);
    MenuInflater inflate = popup.getMenuInflater();
    inflate.inflate(R.menu.cardview_menu, popup.getMenu());
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.delete_id:
                    Posts.remove(position);
                    notifyItemRemoved(position);
                    // do what you need.
                    break;
                default:
                    return false;
            }
            return false;
        }
    });
    popup.show();
}

当我点击我的imagebuttom时出现此错误的任何想法?

1 个答案:

答案 0 :(得分:1)

我假设您在致电View时传递错误showPopup(View view, final int position, final String id)。调用showPopup后,您即可找到特定的观看ID R.id.card_view

View menuItemView = view.findViewById(R.id.card_view);

你通过传递ImageButton本身来调用它

showPopup(holder.imageButtom, position, post.getPid());

我猜测问题的根本原因。我认为您打算传递不同的视图,其中包含您在R.id.card_view中查看的卡片视图(showPopup)。