好吧,我试图像这样在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;
}
}
不知何故,我注意到,当我上下滚动回收的视图时,就会搞砸了……
这里没有滚动图片:
这是滚动后的一个...,您可以看到完全混乱了:
为什么会发生这种情况,如何防止这种情况发生? 有人有解决方案吗?