【问题标题】:Values from checkboxes not working in Android复选框中的值在 Android 中不起作用
【发布时间】:2021-03-18 15:30:06
【问题描述】:

我制作了一个测试应用。当一个或多个复选框被选中并单击一个按钮时,对应于复选框的数字应相加并显示在 textView 中(最初显示为 0)。

MainActivity.java:

public class MainActivity extends AppCompatActivity {

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

        CheckBox rice = findViewById(R.id.rice);
        boolean ateRice = rice.isChecked();

        CheckBox egg = findViewById(R.id.egg);
        boolean ateEgg = egg.isChecked();

        CheckBox bread = findViewById(R.id.bread);
        boolean ateBread = bread.isChecked();

        int cal = countCal(ateRice, ateEgg, ateBread);
        String calString = String.valueOf(cal);

        Button calculate = findViewById(R.id.calculate);

        calculate.setOnClickListener(view -> {
            TextView numCal = findViewById(R.id.cal);
            numCal.setText(calString);
        });

    } //onCreate

    private int countCal(boolean ateRice, boolean ateEgg, boolean ateBread) {
        int calories = 0;
        if(ateRice){
            calories = calories + 20;
        }
        if(ateEgg){
            calories = calories + 50;
        }
        if(ateBread){
            calories = calories + 10;
        }
        return calories;
    } //countCal

}

但是当我点击按钮时,什么都没有发生,并且textView一直显示0。我该怎么办?

(Here's how the app looks)

【问题讨论】:

    标签: java android checkbox


    【解决方案1】:

    您在 OnCreate 中进行所有计算,在活动初始​​化时进行,而不是在发生更改时进行,这就是监听器的来源。

    你需要把countCal计算放到监听器中:

      calculate.setOnClickListener(view -> {
                TextView numCal = findViewById(R.id.cal);
               int cal = countCal(ateRice, ateEgg, ateBread);
               String calString = String.valueOf(cal);
                numCal.setText(calString);
            });
    

    您还需要一个复选框的侦听器,只有在选中/取消选中该项目时,才应更新值 (ateBread)。否则它将根据复选框的初始状态进行计算 例如:

    rice.setOnCheckedChangeListener{ _, isChecked ->
    ateRice = isChecked
    }
    

    【讨论】:

    • 我应该在哪里添加setOnCheckedChangeListener?在 countCal 函数中还是在 onCreate 中?
    • 在 OnCreate 方法中
    猜你喜欢
    • 2019-10-13
    • 2015-11-23
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    相关资源
    最近更新 更多