猿问

如何更改 Recyclerview 所选项目的背景

我很想改变Recyclerview所选项目的背景(只有一个):

爪哇:


public class HorizontalViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ImageView img;

        private SparseBooleanArray selectedItem = new SparseBooleanArray();


        public HorizontalViewHolder(View itemView) {

            super(itemView);

            img = (ImageView) itemView.findViewById(R.id.img);

            itemView.setOnClickListener(this);

        }


        void onBindView(int position) {

            final String s = spacecrafts.get(position);


            Glide.with(c).asBitmap().load(s).apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL))

                    .listener(new RequestListener<Bitmap>() {

                        @Override

                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {

                            return false;

                        }


                        @Override

                        public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {


                            return false;

                        }

                    }).into(img);

        }


        @Override

        public void onClick(View view) {

            monRecyclerViewClickListener.onClick(view, spacecrafts.get(getAdapterPosition()));

            if (selectedItem.get(getAdapterPosition(), false)) {

                selectedItem.clear();

                view.setSelected(false);

            } else {

                selectedItem.put(getAdapterPosition(), true);

                view.setSelected(true);

            }

            // img.setBackgroundDrawable(c.getResources().getDrawable(R.drawable.imagebordertwo));

        }

    }


问题: 当我选择另一个项目时,前一个项目保持选中状态


尚方宝剑之说
浏览 107回答 1
1回答

萧十郎

尝试这个private int selectedIndex = -1;@Overridepublic void onBindViewHolder(ViewHolder holder, int position) {&nbsp; &nbsp; holder.btn1.setOnClickListener( v -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (selectedIndex != position) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectedIndex = position;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; notifyDataSetChanged();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; );&nbsp; &nbsp; // Change here the background of unselected item&nbsp; &nbsp; if (selectedIndex == position) {&nbsp; &nbsp; &nbsp; &nbsp; // Change here the background of selected item&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答