如何将回收程序视图项添加到回收器视图项时重置数据或设置默认数据



我有一个 textView,它包含一个数字值,当单击添加按钮时,它会添加一个,当单击减法按钮时,它会从中减去 1。但是当我将新项目添加到回收器视图时,数字值将自动设置为最后一个项目值。因此,如果第一个项目编号值为 3,则添加第二个项目编号值时将为 3。我希望将新项目添加到回收器视图时文本视图自动为 0

public class PlatesAdapter extends
    RecyclerView.Adapter<PlatesAdapter.ViewHolder> {
//Declaring a List<> of Plates
private List<Plates> mPlatesList;
//Variable to hold total numberOfPlates being used
int amountOfPlates = 0;
String amountOfPlatesString;
//OnBindViewHolder
@Override
public void onBindViewHolder(PlatesAdapter.ViewHolder holder, int position) {
    final TextView amountOfPlatesTextView = holder.amountOfPlatesTextView;
    //BUTTONS add 1 or subtract 1 from amountOfPlates;
    Button addAmountOfPlatesButton = holder.addButton;
    Button subtractAmountOfPlatesButton = holder.subButton;
    addAmountOfPlatesButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addPlates();
            amountOfPlatesString = Integer.toString(amountOfPlates);
            amountOfPlatesTextView.setText(amountOfPlatesString);
        }
    });
    subtractAmountOfPlatesButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            subtractPlates();
            amountOfPlatesString = Integer.toString(amountOfPlates);
            amountOfPlatesTextView.setText(amountOfPlatesString);
        }
    });
}
public void addPlatesLayout(Plates plate) {
    if (mPlatesList == null) mPlatesList = new ArrayList();
    //plate.setPlateWeight(a);
    mPlatesList.add(plate);
    //notifyDataSetChanged();
    notifyItemInserted(mPlatesList.size() - 1);
}
public int addPlates() {
    amountOfPlates++;
    return amountOfPlates;
}
public int subtractPlates() {
    amountOfPlates--;
    return amountOfPlates;
}

只需要在OnBindViewHolder中设置文本。

@Override
public void onBindViewHolder(PlatesAdapter.ViewHolder holder, int position) {
    final TextView amountOfPlatesTextView = holder.amountOfPlatesTextView;
    amountOfPlatesTextView.setText("0");
    //BUTTONS add 1 or subtract 1 from amountOfPlates;
    Button addAmountOfPlatesButton = holder.addButton;
    Button subtractAmountOfPlatesButton = holder.subButton;
    addAmountOfPlatesButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addPlates();
            amountOfPlatesString = Integer.toString(amountOfPlates);
            amountOfPlatesTextView.setText(amountOfPlatesString);
        }
    });
    subtractAmountOfPlatesButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            subtractPlates();
            amountOfPlatesString = Integer.toString(amountOfPlates);
            amountOfPlatesTextView.setText(amountOfPlatesString);
        }
    });
}

最新更新