RecyclerView在滚动时弄乱了子视图

时间:2018-10-26 20:59:43

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

好吧,我试图像这样在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 个答案:

答案 0 :(得分:0)

好吧 当适配器必须在屏幕上重新创建视图时,适配器一直在调用onBindViewHolder()。您需要在getRandomIntInRange()以外的地方致电onBindViewHolder()

您可以看到它: enter image description here