且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用上下文菜单进行Recyclerview时为零

更新时间:2023-11-30 21:36:52

我终于设法按您的要求获取了选定商品ID.

I finally managed to get the Selected Item Id as you requested.

对于此行

AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

menuinfo将始终为null,并且已被多次报告,但仍未解决.我很难设法获得所选列表项的位置,我会给你一些提示.

menuinfo will always be null and It's reported many times but still not solved. I hardly managed to get the position of selected List Item and I will give you some hints of that.

扩展View.OnLongClickListener

extend View.OnLongClickListener

public  class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, View.OnClickListener, View.OnLongClickListener

在ViewHolder内部分配setOnLongClickListener

inside ViewHolder assign setOnLongClickListener

 public ViewHolder(View v) {
            super(v);               
            v.setOnCreateContextMenuListener(this);
            v.setOnLongClickListener(this);

        }

然后onLongClick看起来像这样

@Override
        public boolean onLongClick(View v) {    
            recyclerViewClickListener.recyclerViewListClicked(this.getPosition());
            return false;
        }

其中recyclerViewClickListener是接口而recyclerViewListClicked是方法

public interface RecyclerViewClickListener
{    
    public int recyclerViewListClicked(int position);
}

然后在活动"中创建一个globalVariable,它应该是一个类级变量,并在类似

Then in your Activity create a globalVariable which should be a class level variable and set its value inside the override method which looks like

@Override
    public int recyclerViewListClicked(int position) {
        globalVariable = position;
        return position;
    }

然后,您可以将globalVariable用作此处的所选项目位置

Then after that you can use that globalVariable as selected items position like here

 @Override
    public boolean onContextItemSelected(MenuItem item) {
        Log.d("mySelectedItem", ""+ globalVariable) //use the globalVariable as you need

        return super.onContextItemSelected(item);

    }