我很想改变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)); } }问题: 当我选择另一个项目时,前一个项目保持选中状态
1 回答
萧十郎
TA贡献1815条经验 获得超13个赞
尝试这个
private int selectedIndex = -1;
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.btn1.setOnClickListener( v -> {
if (selectedIndex != position) {
selectedIndex = position;
notifyDataSetChanged();
}
}
);
// Change here the background of unselected item
if (selectedIndex == position) {
// Change here the background of selected item
}
}
添加回答
举报
0/150
提交
取消