RecyclerView 在滚动时弄乱了子视图

Posted

技术标签:

【中文标题】RecyclerView 在滚动时弄乱了子视图【英文标题】:RecyclerView messes up child view on scrolling 【发布时间】:2018-10-26 20:59:42 【问题描述】:

我尝试像这样在 android Studio 中实现 recyclerview:

public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder> 

public String[] dataSet;
public Context context;


//---------------------------------------------------------------------------------------//
//---------------------------------------------------------------------------------------//
//---------------------------------------------------------------------------------------//


public class ViewHolder extends RecyclerView.ViewHolder

    public ImageView image;
    public TextView name;

    public ViewHolder(View itemView) 
        super(itemView);

        this.image = itemView.findViewById(R.id.image);
        this.name = itemView.findViewById(R.id.name);

    

    public void bindData(Object data)

        String extractedData = (String)data;

        this.name.setText("");
        this.name.setText(extractedData);

        this.image.getLayoutParams().height = getRandomIntInRange(250, 100);

    




//---------------------------------------------------------------------------------------//
//---------------------------------------------------------------------------------------//
//---------------------------------------------------------------------------------------//


public RecycleViewAdapter(Context context, String[] dataSet)

    this.context = context;
    this.dataSet = dataSet;



@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 

    View view = LayoutInflater.from(context).inflate(R.layout.food_view,parent,false);
    ViewHolder viewHolder = new ViewHolder(view);

    // Resolves the messed up views after recycling.
    viewHolder.setIsRecyclable(false);

    return viewHolder;


@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) 

    holder.bindData(dataSet[position]);



@Override
public int getItemCount() 
    return dataSet.length;


// Custom method to get a random number between a range
protected int getRandomIntInRange(int max, int min)

    Random rdm = new Random();

    return rdm.nextInt((max-min)+min)+min;

不知何故,我注意到,一旦我上下滚动,回收的视图就会变得一团糟......

这是一张没有滚动的图片:

normal

这是滚动之后的一个......你可以看到完全一团糟:

messed up

为什么会发生这种情况,我该如何防止这种情况发生? 有人有解决办法吗?

【问题讨论】:

【参考方案1】:

嗯 当适配器必须在屏幕上重新创建视图时,适配器一直在调用onBindViewHolder()。您需要在onBindViewHolder()之外拨打getRandomIntInRange()

你可以看到它:

【讨论】:

以上是关于RecyclerView 在滚动时弄乱了子视图的主要内容,如果未能解决你的问题,请参考以下文章

ckeditor在保存时弄乱了代码

VS Code 集成终端在粘贴时弄乱了剪贴板 python 代码

UIScrollView 弄乱了它的子视图

我怀疑 re.match 弄乱了控制流

UIImagePickerController 关闭时弄乱标签栏框架

UITextField 子类弄乱了adjustFontSizeToWidth