简体   繁体   English

recyclerView android上只能点击一项

[英]Only one item may be clicked on recyclerView android

I've a recycler view on my app.我的应用程序有一个回收站视图。 I'd like to prevent multi selections on my recyclerView, because I'm getting unexpected output while trying to delete items.我想防止在我的 recyclerView 上进行多项选择,因为在尝试删除项目时出现意外输出。

        holder.mView.setOnClickListener(v -> {
        if (null != mListener) {
            mListener.onPreviewItemClicked(position);

            if (holder.isSelected) {
                holder.mView.setBackgroundColor(Color.TRANSPARENT);
                Log.d("positionClicked adapter",position+"");
                holder.isSelected = false;
                isSelected = holder.isSelected;
            } else {
                holder.mView.setBackgroundColor(ContextCompat.getColor(mContext, (R.color.accent_light)));
                holder.isSelected = true;
                positionClicked = position;
                isSelected = holder.isSelected;
            }
        }
    });

On my code, I use is Selected boolean to catch if something is clicked.在我的代码中,我使用is Selected布尔值来捕获是否单击了某些内容。 When I click on an item, background of its changes.当我点击一个项目时,它的背景会发生变化。 The thing is :事情是 :

If I click on item1, then on item2, both items have backgrounds changed, and I'd like to have only one.如果我点击 item1,然后点击 item2,这两个项目的背景都改变了,我只想有一个。 And when I click on item, code below is done.当我点击项目时,下面的代码就完成了。 But then, If i click again on item2, it goes transparent, which is good !但是,如果我再次单击 item2,它会变得透明,这很好! But the position of my item selected is wrong ( should be 1, but it's 2 because last item selected was 2).但是我选择的项目的位置是错误的(应该是 1,但它是 2,因为最后选择的项目是 2)。 So when I delete, it will delete 2nd item and not first one...所以当我删除时,它会删除第二个项目而不是第一个......

I delete using positionClicked variable.我使用positionClicked变量删除。

Any idea on how to fix this ?关于如何解决这个问题的任何想法?

You should keep if item is selected in your model, and use it in the onBindViewHolder to setup background for the ViewHolder.如果您的模型中选择了项目,您应该保留,并在onBindViewHolder使用它来设置onBindViewHolder背景。 In OnClickListener just set true for the specific data item, false for all others and then call notifyDataSetChanged() to rebinf all items.OnClickListener只需为特定数据项设置true ,为所有其他项设置 false,然后调用notifyDataSetChanged()重新绑定所有项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM