如何从上下文菜单中获取有关 RecyclerView 项目的信息

How to get information about RecyclerView item from Context Menu

我有一个 RecyclerView 我已经为其实现了 ContextMenu,它在 RecyclerView 项目的 onLongCLick 事件时触发。但是我无法获得在 onMenuItemClick(MenuItem item).

中创建 ContextMenu 的 RecyclerView 项目的位置

适配器中的代码 class:

   public static class PlaceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener,MenuItem.OnMenuItemClickListener {
        protected TextView vName;
        protected TextView vDes;
        protected ImageView vBanner;
        CheckPlacesFragment fragmentCtx;
        ArrayList<UserPlaces> places = new ArrayList<UserPlaces>();
        Context ctx;
        UserPlaces place;

        public PlaceViewHolder(View v, Context ctx, ArrayList<UserPlaces> places, CheckPlacesFragment fragmentCtx) {
            super(v);
            v.setOnClickListener(this);
            v.setOnCreateContextMenuListener(this);
            this.places = places;
            this.ctx = ctx;
            this.fragmentCtx = fragmentCtx;
            vName =  (TextView) v.findViewById(R.id.place_name);
            vDes = (TextView)  v.findViewById(R.id.place_des);
            vBanner = (ImageView) v.findViewById(R.id.banner_img);


        }

        @Override
        public void onClick(View v) {
            int position = getAdapterPosition();
             place = this.places.get(position);
            Toast.makeText(this.ctx,place.getName(),Toast.LENGTH_SHORT).show();


        }


        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            MenuItem deleteAction = menu.add("Delete");
            deleteAction.setOnMenuItemClickListener(this);
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {

           // int id = item.getItemId();
           // ERROR : How to get item position which ContextMenu Created
            switch (id) {
                case 0 :
                    //Call delete Function from Fragment
                    fragmentCtx.test(pid);
                    return true;
                case 1:

                    return true;

            }
            return false;
        }
    }

你可以试试ViewHolder的功能getLayoutPosition().

替换你的onMenuItemClick()
public boolean onMenuItemClick(MenuItem item) {

    int id = item.getItemId();
    int recyclerId = getLayoutPosition();
    place = this.places.get(recyclerId);
    String pid=place.getId();
    switch (id) {
        case 0 :
            //Call delete Function from Fragment
            fragmentCtx.test(pid);
            return true;
        case 1:

            return true;

    }
    return false;
}