回滚视图在滚动时获得更改

时间:2016-01-27 08:39:21

标签: android android-recyclerview recycler-adapter

我正在尝试动态更改RecycleView中的图像。它会成功更改,但是当我滚动RecycleView时,ImageView会得到更改

这是我的适配器类代码:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
    private List<ItemObject> itemList;
    private Context context;
    OnGridSelected onGridObj;
    public RecyclerViewAdapter(Context context, List<ItemObject> itemList,OnGridSelected onGridObj) {
        this.itemList = itemList;
        this.context = context;
        this.onGridObj = onGridObj;
    }
    @Override
    public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
        View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_list, null);
        RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView,itemList,onGridObj);
        return rcv;
    }
    @Override
    public void onBindViewHolder(RecyclerViewHolders holder, int position) {
        if(!itemList.get(position).isSelected()) {
            holder.countryName.setText(itemList.get(position).getName());
            holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
            itemList.get(position).setIsSelected(true);
        }
    }
    @Override
    public int getItemCount() {
        return this.itemList.size();
    }
}

如何防止回收视图获得回收?

2 个答案:

答案 0 :(得分:6)

请试试这个:

如果您使用的是RecycyclerView,请仅覆盖getItemViewType方法。

@Override
public int getItemViewType(int position) {
    return position;
}

答案 1 :(得分:1)

请更改

@Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
    if(!itemList.get(position).isSelected()) {
        holder.countryName.setText(itemList.get(position).getName());
        holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
        itemList.get(position).setIsSelected(true);
    }
}

@Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
        holder.countryName.setText(itemList.get(position).getName());
         holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
    }
}

如果你真的需要isSelected标志,请使用: -

@Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
    if(!itemList.get(position).isSelected()) {
        holder.countryName.setText(itemList.get(position).getName());
        holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
        itemList.get(position).setIsSelected(true);
    }else {
// specify here what to do when is selected is true
}
}

因为每次在屏幕上显示视图时都会调用onBindViewHolder,所以如果isSelected为true,它将永远不会进入条件,因此旧数据将在recyclerview重用视图时可见,所以你应该指定当isSelected应该做什么时应该做什么是的,以便recyclerview可以将数据绑定到它