Android 中 recyclerview 和 viewholder 适配器的错误

Bug with the recycle view and the viewholder adapater in Android

我的应用程序中出现了一个非常奇怪的错误。为了更清楚地说明,我将创建一个带有减号代码的类似示例。

我正在使用 addListenerForSingleValueEventFirebase 实时数据库 读取对象。当我读取对象时,我将它们存储在一个数组中,该数组传递给 Recycleview 中的 Adapter。在这一点上,我可以说,在调试之后,一切似乎都正常工作。

然后在Adapter中,我有类似这样的代码:

public class AdapterObject extends RecyclerView.Adapter<AdapterObject.ViewHolder> {

    ArrayList<Object> objectList;
    Context mContext;

    public AdapterObject (Context context, ArrayList<Object> objectList){
        this.mContext = context;
        this.objectList = objectList;
    }

    @NonNull
    @Override
    public AdapterObject.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.object_grid_layout, parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AdapterObject.ViewHolder holder, int position) {
        Object o = objectList.get(position);
        Log.d("TAG", o.getAtribute());
        if (o.getAtribute().equals("A")){
            holder.atribute.setVisibility(View.VISIBLE);
        }

    @Override
    public int getItemCount() {
        return objectList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        TextView atribute;

        boolean favorite;
        String descuento, precioOriginal;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            atribute = itemView.findViewById(R.id.atribute);
        }
    }
}

在代码中可以看到,如果当前对象的属性值==“A”,那么他的Textview就是显示,否则 Textview 保持隐藏。

调试时一切似乎都是正确的,因为对象及其属性对应于数据库,但是当我在 Android 模拟器中部署应用程序时,我开始在 Recycleview,持有人开始显示 Textviews 尽管控制台调试似乎正确...

这在 RecycleViews 中正常吗?我该如何解决?我找到了,你觉得有什么关系吗?

这是摘自 RecyclerView documentation

As the name implies, RecyclerView recycles those individual elements. When an item scrolls off the screen, RecyclerView doesn't destroy its view. Instead, RecyclerView reuses the view for new items that have scrolled onscreen. This reuse vastly improves performance, improving your app's responsiveness and reducing power consumption.

这意味着当视图被重用时,它将保留当前属性。当 onBindViewHolder 被调用时,您可以更改它们。

在您的具体情况下

@Override
public void onBindViewHolder(@NonNull AdapterObject.ViewHolder holder, int position) {
    Object o = objectList.get(position);
    Log.d("TAG", o.getAtribute());
    if (o.getAtribute().equals("A")){
        holder.atribute.setVisibility(View.VISIBLE);
    } else. {
        holder.atribute.setVisibility(View.GONE);
    }
  }