[英]RecyclerView messes up child view on scrolling
Well i tried to implement the recyclerview into Android Studio like this : 好吧,我试图像这样在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;
}
} }
Somehow i noticed that once i scroll up and down the recycled views get messed up... 不知何故我注意到,一旦我上下滚动,回收的视图就会变得混乱起来。
Heres a Picture without Scrolling : 继承人的图片没有滚动:
And here is one after Scrolling... as you can see totally messed up : 这是滚动之后的一个...如您所见,整个混乱了:
Why does this happen and how can i prevent this ? 为什么会发生这种情况,我该如何预防呢? Does anyone got a solution ? 有人有解决方案吗?
Well Adapter is calling onBindViewHolder()
all times when he must recreate view on the screen. 当适配器必须在屏幕上重新创建视图时,它会一直调用onBindViewHolder()
。 You need to call getRandomIntInRange()
outside of onBindViewHolder()
您需要在onBindViewHolder()
之外调用getRandomIntInRange()
onBindViewHolder()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.