【问题标题】:How to uncheck a radio button in another radio group?如何取消选中另一个单选组中的单选按钮?
【发布时间】:2018-02-05 17:58:57
【问题描述】:

我在一个 xml 文件中有两个无线电组:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

       <RadioButton
            android:id="@+id/btn_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked" />

        <RadioButton
            android:id="@+id/btn_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked" />

    </RadioGroup>

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/btn_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked" />

        <RadioButton
            android:id="@+id/btn_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked" />

    </RadioGroup>

</LinearLayout>

在主要活动中,我可以通过实现onRadioButtonClicked() 方法来处理点击侦听器上的单选按钮:

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.btn_1:

            break;
        case R.id.R.id.btn_2: 

            break;
        case R.id.R.id.btn_3: 

            break;
        case R.id.R.id.btn_4: 

            break;
    }
}

现在,如果选中一个单选按钮,则在同一个单选组中,另一个会自动取消选中。所以这是我的问题:我希望如果一个按钮被选中,那么同一组中的其他按钮和另一个组中的其他按钮都被取消选中。这是可行的吗? 谢谢。

【问题讨论】:

    标签: android radio-button radio-group


    【解决方案1】:

    您可以手动完成。

    case R.id.btn_1:
       btn3.setChecked(false);
       btn4.setChecked(false);
      break;
    case R.id.btn_2:
       btn3.setChecked(false);
       btn4.setChecked(false);
      break;
    case R.id.btn_3:
       btn1.setChecked(false);
       btn2.setChecked(false);
      break;
    case R.id.btn_4:
       btn1.setChecked(false);
       btn2.setChecked(false);
      break;
    

    希望对你有帮助。

    【讨论】:

    • 这看起来很干净,但我怎样才能获得 btn1、btn2、btn3 和 btn4 引用?
    • btn1.setOnCheckedChangeListener()
    • 您可以在单选按钮上添加 setonCheckedChangeListener
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    相关资源
    最近更新 更多