【问题标题】:RecyclerView messes up child view on scrollingRecyclerView 在滚动时弄乱了子视图
【发布时间】: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

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

【问题讨论】:

    标签: java android android-studio view android-recyclerview


    【解决方案1】:

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

    你可以看到它:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-07
      • 2022-06-28
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多