【问题标题】:How to check if a radiobutton is checked in a radiogroup in Android?如何检查单选按钮是否在 Android 的单选组中被选中?
【发布时间】:2014-09-19 12:06:21
【问题描述】:

我需要设置用户必须填写/选择页面中所有详细信息的验证。如果任何字段为空想显示Toast message to fill. 现在我需要在RadioGroup. 中为RadioButton 设置验证我尝试了这段代码但没有正常工作。建议我正确的方法。谢谢。

// get selected radio button from radioGroup
int selectedId = gender.getCheckedRadioButtonId();
// find the radiobutton by returned id
selectedRadioButton = (RadioButton)findViewById(selectedId);
// do what you want with radioButtonText (save it to database in your case)
radioButtonText = selectedRadioButton.getText().toString();

if(radioButtonText.matches(""))
{
    Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
    Log.d("QAOD", "Gender is Null");
}
else
{
    Log.d("QAOD", "Gender is Selected");
}

【问题讨论】:

  • if(radioGroup.getCheckedRadioButtonId()==radioGroup.getChildAt(radio1).getId()) { 收音机 1 被选中; } else if(..... == radioGroup.getChildAt(radio2)) { 收音机 2 被选中; } ...使用它,您可以获得选定的单选值。 :)
  • 嗨@RipalTamboli 感谢您的评论,但我可以获得单选按钮的值和文本。我需要验证用户是否不检查性别(无线电组),单击按钮时会显示错误消息。
  • 好的。你能检查一下,如果没有选择任何选项,那么 getCheckedRadioButtonID() 返回什么?如果它返回 null / -1,那么您的工作是通过检查它是否为 null / -1 来完成的。 :) 性别组中的 nwys,默认情况下始终需要选择一个选项。这是设计它的标准方式:) .. 如果有任何疑问,请告诉我。

标签: android radio-button radio-group


【解决方案1】:

如果您只想检查一个RadioButton,您可以使用isChecked 函数

if(radioButton.isChecked())
{
  // is checked    
}
else
{
  // not checked
}

如果你有RadioGroup,你可以使用

if (radioGroup.getCheckedRadioButtonId() == -1)
{
  // no radio buttons are checked
}
else
{
  // one of the radio buttons is checked
}

【讨论】:

  • 非常有帮助。感谢您的回答。
【解决方案2】:

您需要做的就是使用getCheckedRadioButtonId()isChecked() 方法,

if(gender.getCheckedRadioButtonId()==-1)
{
    Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
}
else
{
    // get selected radio button from radioGroup
    int selectedId = gender.getCheckedRadioButtonId();
    // find the radiobutton by returned id
    selectedRadioButton = (RadioButton)findViewById(selectedId);
    Toast.makeText(getApplicationContext(), selectedRadioButton.getText().toString()+" is selected", Toast.LENGTH_SHORT).show();
}

https://developer.android.com/guide/topics/ui/controls/radiobutton.html

【讨论】:

    【解决方案3】:

    对您必须检查的每个单选按钮使用 isChecked() 函数

    RadioButton maleRadioButton, femaleRadioButton;
    
    maleRadioButton = (RadioButton) findViewById(R.id.maleRadioButton);
    femaleRadioButton = (RadioButton) findViewById(R.id.femaleRadioButton);
    

    然后将结果用于您的 if/else 案例考虑。

    if (maleRadioButton.isChecked() || femaleRadioButton.isChecked()) {
         Log.d("QAOD", "Gender is Selected");
    } else {
        Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
        Log.d("QAOD", "Gender is Null");
    }
    

    【讨论】:

    • 您好,感谢您的回答,我需要检查整个 Radio Group 而不是单个 Radio Button。
    【解决方案4】:
      rgrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch(i) {
                    case R.id.type_car:
                        num=1;
                        Toast.makeText(getApplicationContext()," Car",Toast.LENGTH_LONG).show();
                        break;
                    case R.id.type_bike:
                        num=2;
                        Toast.makeText(getApplicationContext()," Bike",Toast.LENGTH_LONG).show();
                        break;
                }
            }
        });
    

    【讨论】:

      【解决方案5】:

      尝试使用方法isChecked();

      喜欢,

      selectedRadioButton.isChecked() -> 返回布尔值。

      有关单选按钮的更多详细信息,请参阅here

      【讨论】:

      • 感谢您的回答,我需要检查整个 Radio Group 而不是单个 Radio Button。
      • here 你去吧。使用 RadioGroup 上的 getCheckedRadioButtonId() 方法来找出答案。当未选择组中的 RadioButton 时,它返回 -1。你已经在这样做了。因此,如果 selectedId 为 -1,则表示未选择性别。否则会在组中选择某些内容。
      【解决方案6】:

      尝试使用这个

      <RadioGroup
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"       
          android:orientation="horizontal"
      >    
          <RadioButton
              android:id="@+id/standard_delivery"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/Standard_delivery"
              android:checked="true"
              android:layout_marginTop="4dp"
              android:layout_marginLeft="15dp"
              android:textSize="12dp"
              android:onClick="onRadioButtonClicked"   
          />
      
          <RadioButton
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/Midnight_delivery"
              android:checked="false"
              android:layout_marginRight="15dp"
              android:layout_marginTop="4dp"
              android:textSize="12dp"
              android:onClick="onRadioButtonClicked"
              android:id="@+id/midnight_delivery"
          />    
      </RadioGroup>
      

      这是java类

      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.standard_delivery:
                      if (checked)
                          Toast.makeText(DishActivity.this," standard delivery",Toast.LENGTH_LONG).show();
                          break;
                  case R.id.midnight_delivery:
                      if (checked)
                          Toast.makeText(DishActivity.this," midnight delivery",Toast.LENGTH_LONG).show();
                          break;
              }
          }
      

      【讨论】:

        【解决方案7】:

        我使用了以下内容,它对我有用。我使用了一个布尔验证函数,如果选中了 Radio Group 中的任何 Radio Button,则验证函数返回 true 并进行提交。如果返回 false,则不提交,并显示“Select Gender”祝酒词:

        1. MainActivity.java

          public class MainActivity extends AppCompatActivity {
              private RadioGroup genderRadioGroup;
          
              @Override
              protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
          
              //Initialize Radio Group And Submit Button
              genderRadioGroup=findViewById(R.id.gender_radiogroup);
              AppCompatButton submit = findViewById(R.id.btnSubmit);
          
              //Submit Radio Group using Submit Button
              submit.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      //Check Gender radio Group For Selected Radio Button
                      if(genderRadioGroup.getCheckedRadioButtonId()==-1){//No Radio Button Is Checked
                          Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG).show();
                      }else{//Radio Button Is Checked
                          RadioButton selectedRadioButton = findViewById(genderRadioGroup.getCheckedRadioButtonId());
                          gender = selectedRadioButton == null ? "" : selectedRadioButton.getText().toString().trim();
                      }
                      //Validate
                      if (validateInputs()) {
                          //code to proceed when Radio button is checked
                      }
                  }
              }
              //Validation - No process is initialized if no Radio button is checked
              private boolean validateInputs() {
                  if (genderRadioGroup.getCheckedRadioButtonId()==-1) {
                      return false;
                  }
                  return true;
              }
          }
          
        2. 在activity_main.xml中:

          <LinearLayout
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:orientation="horizontal">
          
              <TextView
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:text="@string/gender"/>
          
              <RadioGroup
                      android:id="@+id/gender_radiogroup"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:orientation="horizontal">
          
                  <RadioButton
                          android:id="@+id/male"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:text="@string/male"/>
          
                  <RadioButton
                          android:id="@+id/female"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:text="@string/female""/>
          
              </RadioGroup>
          
              <android.support.v7.widget.AppCompatButton
                  android:id="@+id/btnSubmit"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:text="@string/submit"/>
          
          </LinearLayout>
          

        如果没有选择性别单选按钮,则继续执行的代码将不会运行。

        我希望这会有所帮助。

        【讨论】:

        • 你能补充一些关于它的作用以及它为什么能解决问题的 cmets 吗?
        • 我在上面的帖子中添加了 cmets。我希望 cmets 展示代码的作用以及它解决问题的原因。
        【解决方案8】:

        我使用单选按钮的 ID 与使用 mRadioGroup.getCheckedRadioButtonId() 获得的 checkedRadioButton 的 ID 进行比较

        这是我的代码:

        mRadioButton1=(RadioButton)findViewById(R.id.first);
        mRadioButton2=(RadioButton)findViewById(R.id.second);
        mRadioButton3=(RadioButton)findViewById(R.id.third);
        mRadioButton4=(RadioButton)findViewById(R.id.fourth);
        
        mNextButton=(Button)findViewById(R.id.next_button);
        
        mNextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedId=mRadioGroup.getCheckedRadioButtonId();
        
                int n=0;
                if(selectedId==R.id.first){n=1;}
        
                else if(selectedId==R.id.second){n=2;}
        
                else if(selectedId==R.id.third){n=3;}
        
                else if(selectedId==R.id.fourth){n=4;}
                //. . . .
            }
        

        【讨论】:

          【解决方案9】:

          我的回答是根据the documentation,效果很好。

          1) 在xml文件中包含android:onClick="onRadioButtonClicked"如下图:

          <RadioGroup
          android:id="@+id/rg1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="vertical"
          android:gravity="center">
          <RadioButton
              android:id="@+id/b1"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="onCreateOptionsMenu()"
              android:onClick="onRadioButtonClicked"
                      />
          <RadioButton
              android:id="@+id/b2"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="onCreateMenu()"
              android:onClick="onRadioButtonClicked"
                      />
          </RadioGroup>
          

          2) 在Java文件中,在onCreate()方法之外实现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.b1:
                      if (checked)
                      {
                          Log.e("b1", "b1" );
                          break;
                      }
                  case R.id.b2:
                      if (checked)
                          break;
              }
          }
          

          【讨论】:

            【解决方案10】:
            mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup radioGroup, int i) {
                        if (mRadioButtonMale.isChecked()) {
                            text = "male";
                        } else {
                            text = "female";
                        }
                    }
                });
            

             mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup radioGroup, int i) {
                        if (mRadioButtonMale.isChecked()) { text = "male"; }
                        if(mRadioButtonFemale.isChecked()) { text = "female"; }
                    }
                });
            

            【讨论】:

              【解决方案11】:
              radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                          @Override
                          public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                              checkedId = radioGroup.getCheckedRadioButtonId();
              
                              switch (checkedId) {
                                  case R.id.expert_rb:
                                      // do something
                                      break;
                                  case R.id.no_expert_rb:
                                      // do something else
                                      break;
                                 
                              }
                          }
                      });
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2016-01-11
                • 2012-06-18
                • 2020-12-04
                • 2019-12-21
                • 1970-01-01
                • 2014-02-06
                相关资源
                最近更新 更多