首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Android的电台组中检查是否勾选了某个单选按钮?

如何在Android的电台组中检查是否勾选了某个单选按钮?
EN

Stack Overflow用户
提问于 2014-07-28 18:08:46
回答 8查看 207.9K关注 0票数 83

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

代码语言:javascript
复制
// 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");
}
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2014-07-28 18:15:36

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

代码语言:javascript
复制
if(radioButton.isChecked())
{
  // is checked    
}
else
{
  // not checked
}

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

代码语言:javascript
复制
if (radioGroup.getCheckedRadioButtonId() == -1)
{
  // no radio buttons are checked
}
else
{
  // one of the radio buttons is checked
}
票数 229
EN

Stack Overflow用户

发布于 2014-07-28 18:15:47

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

代码语言:javascript
复制
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

票数 24
EN

Stack Overflow用户

发布于 2019-08-02 18:09:06

代码语言:javascript
复制
  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;
            }
        }
    });
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24992936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档