我有一个使用RecyclerView.ViewHolder的Horizontal CardView和ViewHolder。 我想在cardView中单击图像时设置一个额外的图像(选中的图标)。 在我的卡片视图中,我有7张照片。当我点击第一张图片时,所选图标设置正确。但是这个图标也设置在第6张图片上。 如果我在卡片视图中点击第2张图片,则会在第7张图片上自动设置图标。
这里有什么问题? 我该如何防止这种行为?
感谢。
public class CVAreaAdapter extends RecyclerView.Adapter<CVAreaAdapter.AreaViewHolder> {
List<Area> areaList;
Activity activity;
static AreaViewHolder prevHolder = null;
public CVAreaAdapter(List<Area> areaList, Activity activity){
this.areaList = areaList;
this.activity = activity;
}
public static class AreaViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView areaName;
ImageView areaPhoto;
ImageView selectedIcon;
String currentItemName;
int areaId;
boolean iconVisible = false;
AreaViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
areaName = (TextView)itemView.findViewById(R.id.cv_item_area_name);
areaPhoto = (ImageView)itemView.findViewById(R.id.cv_item_area_photo);
selectedIcon = (ImageView) itemView.findViewById(R.id.cv_selected_icon);
}
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public AreaViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.area_cv_item_horizontal, viewGroup, false);
final AreaViewHolder areaViewHolder = new AreaViewHolder(v);
v.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
// item clicked
Toast.makeText(activity, "selected areaName: "
+ areaViewHolder.currentItemName, Toast.LENGTH_SHORT).show();
updateIcon(areaViewHolder);
}
});
return areaViewHolder;
}
@Override
public void onBindViewHolder(final AreaViewHolder areaViewHolder, int i) {
areaViewHolder.areaName.setText(areaList.get(i).getName());
areaViewHolder.areaPhoto.setImageResource(areaList.get(i).getImageId());
areaViewHolder.currentItemName = (areaList.get(i).getName());
areaViewHolder.areaId = (areaList.get(i).getId());
}
@Override
public int getItemCount() {
return areaList.size();
}
public void updateIcon(AreaViewHolder areaViewHolder){
if(getPrevHolder() != null) {
// remove selected icon from previous picture
hideIcon(getPrevHolder());
}
setIcon(areaViewHolder);
}
private void setIcon(AreaViewHolder areaViewHolder){
if(!areaViewHolder.iconVisible ) {
showIcon(areaViewHolder);
} else{
hideIcon(areaViewHolder);
}
setPrevHolder(areaViewHolder);
}
public void hideIcon(AreaViewHolder areaViewHolder){
areaViewHolder.selectedIcon.setVisibility(View.GONE);
areaViewHolder.iconVisible = false;
}
public void showIcon(AreaViewHolder areaViewHolder){
areaViewHolder.iconVisible = true;
areaViewHolder.selectedIcon.setVisibility(View.VISIBLE);
}
public void setPrevHolder(AreaViewHolder areaViewHolder){
this.prevHolder = areaViewHolder;
}
public AreaViewHolder getPrevHolder(){
return this.prevHolder;
}
}