在我的recyclerview中有一个imageview和textview。我正在更改ImageView on onClickListener
的图像。现在的问题是,如果我点击位置3的图像并向下滚动...位置8的图像也会改变,如果我向上滚动......位置2的图像也会改变。
public class PortraitListviewAdapter extends RecyclerView.Adapter<PortraitListviewAdapter.ViewHolder> {
Context context;
static List<PortraitParentListAdapterBean> list;
static List<String> selectedPosition ;
public PortraitListviewAdapter(Context context, List<PortraitParentListAdapterBean> list) {
this.context = context;
this.list = list;
selectedPosition = new ArrayList<>();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listview_parent_portrait, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
PortraitParentListAdapterBean portBean = list.get(position);
Log.i("pos",position+"");
holder.parentHeading.setText(portBean.getHeading());
if (selectedPosition.contains(list.get(position).getHeading())){
holder.parentImage.setImageResource(R.drawable.sad);
}
}
@Override
public int getItemCount() {
return list.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
protected TextView parentHeading;
protected ImageView parentImage;
public ViewHolder(View itemView) {
super(itemView);
parentHeading = (TextView)itemView.findViewById(R.id.parent_heading);
parentImage = (ImageView)itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedPosition.add(list.get(getAdapterPosition()).getHeading());
parentImage.setImageResource(R.drawable.sad);
}
});
}
}
}
上面的代码是我对recyclerview适配器的实现。请帮助理解这个概念。
答案 0 :(得分:0)
<强>解强>
变化
if (selectedPosition.contains(list.get(position).getHeading())){ holder.parentImage.setImageResource(R.drawable.sad); }
与
if (selectedPosition.contains(list.get(position).getHeading())){ holder.parentImage.setImageResource(R.drawable.sad); } else { holder.parentImage.setImageResource(R.drawable.your_default_drawable); }
<强>说明强>
当您滚动RecyclerView时,系统不会重新创建您的ViewHolder,而是重复使用之前滚动的不再可见的视频,因此您需要重置标准值以避免显示错误的值。