基于RadioGroup与数量增减按钮实现小计金额计算问题求助
解决方案:实现数量增减与单价联动计算小计
要实现数量变化时自动更新小计,核心是保存当前选中的单价,并在数量或单价变化时重新计算金额。以下是具体修改方案:
1. 添加存储当前单价的变量
在类中新增成员变量,用于记录当前选中商品的单价:
private int currentPrice = 0; // 存储当前选中商品的单价
2. 修改单选按钮点击事件
不再直接设置小计文本,先更新currentPrice,再调用统一的小计更新方法:
public void RButton (View v){ int radioID = radioGroup.getCheckedRadioButtonId(); switch(radioID){ case R.id.type1: currentPrice = 5; break; case R.id.type2: currentPrice = 10; break; case R.id.type3: currentPrice = 12; break; } updateSubtotal(); // 更新小计 }
3. 新增小计更新方法
封装计算逻辑,统一处理金额计算和文本显示:
private void updateSubtotal() { int subtotal = count * currentPrice; textView.setText("$" + subtotal); }
4. 修改增减按钮方法
更新数量后,调用updateSubtotal()同步更新小计:
public void plus (View v){ count++; value.setText("" + count); updateSubtotal(); } public void minus (View v){ if (count <= 0 ) count = 0; else count--; value.setText("" + count); updateSubtotal(); }
5. (可选)初始化默认选中状态
为避免初始状态小计为0,可在onCreate中默认选中一个单选按钮并初始化单价:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_expresso_item1); value = findViewById(R.id.quantity1); radioGroup = findViewById(R.id.radioGroup); textView = findViewById(R.id.total1); // 默认选中第一个单选按钮并初始化单价 RadioButton defaultRadio = findViewById(R.id.type1); defaultRadio.setChecked(true); currentPrice = 5; updateSubtotal(); }
修改后的完整代码
public class expresso_item1 extends AppCompatActivity { private RadioGroup radioGroup; private TextView textView; private TextView value; private int count = 0; private int currentPrice = 0; // 存储当前选中商品的单价 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_expresso_item1); value = findViewById(R.id.quantity1); radioGroup = findViewById(R.id.radioGroup); textView = findViewById(R.id.total1); // 默认选中第一个商品类型并初始化 RadioButton defaultRadio = findViewById(R.id.type1); defaultRadio.setChecked(true); currentPrice = 5; updateSubtotal(); } public void RButton (View v){ int radioID = radioGroup.getCheckedRadioButtonId(); switch(radioID){ case R.id.type1: currentPrice = 5; break; case R.id.type2: currentPrice = 10; break; case R.id.type3: currentPrice = 12; break; } updateSubtotal(); } public void plus (View v){ count++; value.setText("" + count); updateSubtotal(); } public void minus (View v){ if (count <= 0 ) count = 0; else count--; value.setText("" + count); updateSubtotal(); } private void updateSubtotal() { int subtotal = count * currentPrice; textView.setText("$" + subtotal); } }
这样修改后,无论是切换商品类型还是调整数量,小计金额都会自动更新,完全符合需求。
内容的提问来源于stack exchange,提问作者Ivor
相关产品推荐
相关产品推荐

