如何在Android中检查radiogroup中的radiobutton是否被选中?

86

我需要设置验证,以确保用户必须填写/选择页面中的所有细节。如果有任何字段为空,就要显示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");
}

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

250

如果你想检查一个 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
}

非常有帮助。感谢回答。 - Pooja

28
你只需要使用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


8

对于每个需要检查的单选按钮,请使用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");
}

嗨,谢谢你的回答,我需要检查整个单选按钮组而不是单个单选按钮。 - Srihari

6
  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

我用了下面的方法,它对我有用。我使用了一个布尔类型的验证函数,如果 Radio Group 中的任何一个单选按钮被选中,则验证函数返回 true 并进行提交。如果返回 false,则不进行提交并显示 "请选择性别" 的提示信息:

  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. In 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>
    

如果没有选择性别单选按钮,则无法运行继续的代码。

希望这可以帮到您。


你能否添加一些注释,说明这段代码的作用以及为什么它解决了问题? - Matt C
1
我已经在上面的帖子中添加了注释。我希望这些注释能展示代码的功能并解释为什么它们可以解决问题。 - profjack

4

我使用单选按钮的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;}
        //. . . .
    }

4

试着使用这个

<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;
        }
    }

4

尝试使用isChecked()方法;

例如,

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

关于单选按钮的更多详细信息,请参考这里


谢谢您的回答,我需要检查整个单选按钮组而不是单个单选按钮。 - Srihari
1
在这里,使用RadioGroup的getCheckedRadioButtonId()方法来查找。当组中没有选中任何RadioButton时,它返回-1。您已经在执行此操作。因此,如果selectedId为-1,则表示未选择任何性别。否则,组中选择了某些内容。 - balachandarkm

1
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;
                   
                }
            }
        });

1
我的答案是根据文档,它可以很好地工作。
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文件中实现onRadioButtonClicked方法,将其放置在onCreate()方法之外,如下所示:

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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接