【问题标题】:checking if all radiogroups in an activity are checked检查是否检查了活动中的所有无线电组
【发布时间】:2014-07-04 12:09:50
【问题描述】:

我的一项活动中有一个表格,大约有 10 个无线电组。我的问题是我必须检查是否有一个无线电组没有检查? 我的代码示例如下所示:

    <RadioGroup
        android:id="@+id/radioq1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/q1f"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:text="@string/conffalse"
            android:textColor="#f05252" />

        <RadioButton
            android:id="@+id/q1t"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="60dp"
            android:text="@string/conftrue"
            android:textColor="#37df47" />

     </RadioGroup>

【问题讨论】:

  • 你有 10 个单选组或按钮?
  • 您应该使用 CheckBox 而不是 RadioButton/RadioGroup?因为您必须检查多个项目。
  • @PurpleDroid 是的,他有上述代码 10 次

标签: java android foreach


【解决方案1】:

您可以检查是否有任何按钮在 radioGroup 中被选中:

int checkId =  yourRadioGroup.getCheckedRadioButtonId();

boolean isChecked = false;

if(checkedId==-1){

    isChecked=false;
 }else{

    isChecked=true;
}

对每个 RadioGroup 执行此操作,例如使用包含每个 Radiogroup 和 for 循环的数组:

RadioGroup[] groups = new RadioGroup{RadioGroup1,RadioGroup2};

for(int i=0;i<groups.length;i++){

 int id = groups[i].getCheckedRadioButtonId();
 if(id==-1){

  isChecked=false;
  break; //break the loop, because if one is not checked, inform the user
 }else{

   isChecked=true;
  }
}

方法getCheckedRadioButtonId();如果没有选中单选按钮,则返回 -1。

【讨论】:

    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 2018-03-27
    相关资源
    最近更新 更多