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

时间:2016-06-28 11:40:04

标签: android android-recyclerview contextmenu

我有一个RecyclerView,我已经实现了ContextMenu,它在RecyclerView项目的onLongCLick事件时被触发。但我无法获得在ContextMenu内创建onMenuItemClick(MenuItem item)的RecyclerView项目的位置。

我的适配器类中的代码:

   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;
        }
    }

2 个答案:

答案 0 :(得分:3)

将您的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;
}

答案 1 :(得分:2)

您可以尝试ViewHolder的功能getLayoutPosition()