如何从用户输入向列表添加数据

How to add data to list from user input

我在向列表中添加数据时遇到问题。 用户必须输入数据,然后在使用模型 class.

RecycleView 中显示数据

应用程序运行正常,但 RecycleView 上未显示数据。 在一切正常之前,我添加了一个 Swipe 方法来从 RecycleView 中删除项目,并且我必须将项目数据连接到模型 class。 所以,我的大问题是如何将数据添加到列表中。 提前致谢

我认为主要问题是这部分代码:

private void saveInfo() {
String ingredientName = ingrName.getText().toString();
int ingQuant = Integer.valueOf(ingrQuantity.getText().toString());

list.add(new CalculatorItemModel(ingredientName,String.valueOf(ingQuant)));

这是我的模型Class

public class CalculatorItemModel {

private String ingName, ingQuantity;

public CalculatorItemModel(String ingName, String ingQuantity) {
    this.ingName = ingName;
    this.ingQuantity = ingQuantity;
}

public String getIngName() {
    return ingName;
}

public void setIngName(String ingName) {
    this.ingName = ingName;
}

public String getIngQuantity() {
    return ingQuantity;
}

public void setIngQuantity(String ingQuantity) {
    this.ingQuantity = ingQuantity;
}

}

还有我的Activity

public class CalculatorActivity extends AppCompatActivity implements CallBackItemTouch{

Button btnCclcola;
TextView cancel, doneBtn, nameTV, quantityTV, resulttry;
EditText ingrName, ingrQuantity, moltiplyN;
Dialog dialog;
RecyclerView recyclerView;

List<CalculatorItemModel> list;
ConstraintLayout constraintLayout;
private CalculatorAdapter calculatorAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_calculator);

    nameTV = findViewById(R.id.nameTV);
    quantityTV = findViewById(R.id.qunatityTV);
    btnCclcola = findViewById(R.id.btn_calcola);

    recyclerView = findViewById(R.id.rv_calculator);
    recyclerView.setHasFixedSize(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);


    calculatorAdapter = new CalculatorAdapter(list);
    recyclerView.setAdapter(calculatorAdapter);


    dialog = new Dialog(this);

    btnCclcola.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            int total = 0;

            for (int i = 0; i < list.size(); i++) {
                int total2 = Integer.parseInt(quantity.get(i));
                total += total2;
                
                Toast.makeText(CalculatorActivity.this, ""+ total, Toast.LENGTH_SHORT).show();
            }

        }
    });
}


private void saveInfo() {
    String ingredientName = ingrName.getText().toString();
    int ingQuant = Integer.valueOf(ingrQuantity.getText().toString());

    list.add(new CalculatorItemModel(ingredientName,String.valueOf(ingQuant)));

}

将项目添加到列表后调用 calculatorAdapter.notifyDataSetChanged()