我有这段代码:
CheckBox aud = (CheckBox)findViewById(R.id.aud);
CheckBox cad = (CheckBox)findViewById(R.id.cad);
CheckBox usd = (CheckBox)findViewById(R.id.usd);
CheckBox gbp = (CheckBox)findViewById(R.id.gbp);
CheckBox eur = (CheckBox)findViewById(R.id.eur);
和此:
int m = 0;
if (aud.isChecked()){
m+= 1;
}
if (cad.isChecked()){
m+= 1;
}
if (usd.isChecked()){
m+= 1;
}
if (gbp.isChecked()){
m+= 1;
}
if (eur.isChecked()){
m+= 1;
}
if (m > 1){
aud.setChecked(false);
gbp.setChecked(false);
usd.setChecked(false);
cad.setChecked(false);
eur.setChecked(false);
m = 0;
Toast.makeText(this, "Please select only one currency", Toast.LENGTH_SHORT).show();
}if (m == 0){
Toast.makeText(this, "Please select a currency", Toast.LENGTH_SHORT).show();
}else{
this.currency = //add the value of the selected checkbox
我需要将唯一选中的复选框的值添加到currecny变量中。我设法检查是否只有一个选中,但我无法弄清楚如何获取所选的值并将其放在一个名为currency的变量中,这是一个类属性。
答案 0 :(得分:3)
尝试使用RadioGroup
RadioGroup rd= (RadioGroup)findViewById(R.id.radioGroup1);
rd.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
RadioButton rb=(RadioButton)findViewById(checkedId);
Toast.makeText(getApplicationContext(), rb.getText(), Toast.LENGTH_SHORT).show();
// rb.getText() = to get Value
}
});
xml:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="180dp"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="CAD" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EUR" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TUN" />
</RadioGroup>