java - 多个复选框。仅选择一项。如何获得它的值

标签 java android checkbox

我有这个代码:

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变量中。我设法检查是否只选择了一个,但我不知道如何获取所选值并将其放置在名为货币的变量中,该变量是一个类属性。

最佳答案

尝试使用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>

关于java - 多个复选框。仅选择一项。如何获得它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28142162/

相关文章:

java - 加载 JNI 库时出现 Unsatisfied Link 错误

java - Paypal REST API 中的 Braintree 计费协议(protocol) ID 查找

android - ListView : filtering via Filterable vs. 使用新 URI 重新启动 CursorLoader

android - 我是否需要我的移动应用程序中的私钥才能通过 SSL 与服务器通信?

java - 加点机制麻烦?

javascript - Django 模板 - 选择时复选框没有反应

java - 正则表达式向前将字符串分隔成标记

java - 无法安装maven

ios - 图像复选框问题

javascript - JQuery 验证器自定义错误放置不起作用