如何检查单选按钮是否在 Android 的单选组中被选中?

How to check if a radiobutton is checked in a radiogroup in Android?(如何检查单选按钮是否在 Android 的单选组中被选中?)

本文介绍了如何检查单选按钮是否在 Android 的单选组中被选中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to set validation that user must fill / select all details in a page. If any fields are empty wanna show Toast message to fill. Now I need set validation for RadioButton in the RadioGroup. I tried this code but didn't work properly. Suggest me correct way. Thankyou.

// 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");
}

推荐答案

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

If you want to check on just one RadioButton you can use the isChecked function

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

如果你有一个 RadioGroup 你可以使用

and if you have a RadioGroup you can use

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

这篇关于如何检查单选按钮是否在 Android 的单选组中被选中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何检查单选按钮是否在 Android 的单选组中被选中?

基础教程推荐