You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android复选框选中价格计算异常:点击复选框跳转主页问题排查

问题分析与修复方案

核心问题排查

  1. 点击复选框跳回主页的根本原因:
    布局中大概率给CheckBox绑定了android:onClick="calculateTDEE",点击复选框触发计算逻辑时,若成人/儿童票数量输入框为空,Integer.parseInt()会抛出NumberFormatException,导致Activity崩溃,系统自动回到主页。

  2. 功能逻辑错误:

    • RadioButton选中状态判断错误:误用isSelected()(视图选中状态,如焦点)代替isChecked()(单选按钮选中状态),导致影厅类型判断始终出错。
    • 复选框价格逻辑错误:选中多个复选框时,sum会被最后一个选中项的价格覆盖,而非累加所有选中项的价格。

修复后的代码

public class movie1 extends AppCompatActivity {

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

    public void calculateTDEE(View view) {
        // 修复RadioButton选中判断逻辑
        String hall;
        RadioButton rb1 = findViewById(R.id.rb1);
        if (rb1.isChecked()) {
            hall = "2D";
        } else {
            hall = "MX4D";
        }

        // 修复复选框价格累加逻辑
        double sum = 0;
        CheckBox cb1 = findViewById(R.id.cb1);
        if (cb1.isChecked()) {
            sum += 14.50;
        }
        CheckBox cb2 = findViewById(R.id.cb2);
        if (cb2.isChecked()) {
            sum += 18.50;
        }
        CheckBox cb3 = findViewById(R.id.cb3);
        if (cb3.isChecked()) {
            sum += 14.50;
        }

        // 处理输入框为空的情况,避免崩溃
        EditText etAdult = findViewById(R.id.etAdult);
        int adult = 0;
        if (!etAdult.getText().toString().trim().isEmpty()) {
            adult = Integer.parseInt(etAdult.getText().toString());
        }

        EditText etChild = findViewById(R.id.etChild);
        int child = 0;
        if (!etChild.getText().toString().trim().isEmpty()) {
            child = Integer.parseInt(etChild.getText().toString());
        }

        // 计算最终总价
        double totalPrice = 0.00;
        if (hall.equals("2D")) {
            totalPrice = (10.00 * child) + (21.50 * adult) + sum;
        } else {
            totalPrice = (18.00 * child) + (30.50 * adult) + sum;
        }

        // 格式化显示结果
        TextView tvResult = findViewById(R.id.tvResult);
        tvResult.setText(String.format("订单已确认!总价:%.2f 元,请至柜台支付", totalPrice));
    }
}

布局补充修复

如果复选框仅作为选项勾选,不需要触发计算逻辑,需移除布局中所有CheckBox的android:onClick="calculateTDEE"属性,仅给专门的「计算/确认」按钮设置该点击事件。

内容的提问来源于stack exchange,提问作者Fatihah Shazeera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 19:52:37