【问题标题】:radio button is checked, still isChecked() returns false in android选中单选按钮,仍然 isChecked() 在 android 中返回 false
【发布时间】:2015-10-01 10:55:30
【问题描述】:

我在活动中遇到单选按钮问题。我在一个单选组中添加了两个单选按钮。

<RadioGroup
                    android:layout_width="270dp"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:gravity="center_vertical">
                    <RadioButton
                        android:id="@+id/site_automation_yes"
                        android:layout_width="100dp"
                        android:layout_height="wrap_content"
                        android:text="YES"
                        android:button="@drawable/apptheme_btn_radio_holo_light"
                        android:textSize="18dp"/>
                    <RadioButton
                        android:id="@+id/site_automation_no"
                        android:layout_width="100dp"
                        android:layout_height="wrap_content"
                        android:text="NO"
                        android:button="@drawable/apptheme_btn_radio_holo_light"
                        android:textSize="18dp"/>
                </RadioGroup>

当我检查 site_automation_yes 单选按钮时,isChecked() 仍然返回 false。 同样在创建活动时第一次,我无法检查“site_automation_no”单选按钮。但是,当我首先检查 site_automation_yes 时,我可以检查和取消选中这两个单选按钮。但是对于 site_automation_yes isChecked 总是返回 false,不管它是否被选中。有人可以告诉我如何解决这个问题。 提前致谢。

【问题讨论】:

    标签: android


    【解决方案1】:

    如果你想要选中的收音机,那么你必须遵循这个: 1.给广播组id 2. 使用下面的例子:

    int selectedId = radioSexGroup.getCheckedRadioButtonId();
    
    // find the radiobutton by returned id
    radioSexButton = (RadioButton) findViewById(selectedId);
    
    Toast.makeText(MyAndroidAppActivity.this,
                    radioSexButton.getText(), Toast.LENGTH_SHORT).show();
    

    这里,radioSexGroup 是一个 RadioGroup id。通过 getCheckedRadioButtonId() 获取选中的单选按钮;然后只需获取选中的单选按钮的名称。

    【讨论】:

    • 如果两者都未选中会怎样?
    • 如果您想预先选择任何选项,那么您不必在 radioSexButton 处检查 null。如果您不想预先选择任何选项,请在 radioSexButton 上检查 null。
    • 我必须保持两者都未选中。
    • 只检查 if(radioSexButton != null) 然后不要做其他事情。
    • isChecked 问题已解决。但问题的另一部分仍未得到解答。
    猜你喜欢
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多