简体   繁体   English

如何获取buttonGroup的选定radioButton的值

[英]How to get value of selected radioButton of buttonGroup

How to get value of selected radioButton ?如何获取所选radioButton值? I tried using buttonGroup1.getSelection().getActionCommand() (as posted in some of answers here) but it is not working.我尝试使用buttonGroup1.getSelection().getActionCommand() (如此处的一些答案中所述)但它不起作用。 Also, i am temporarily using this code but i want to know is this a good practice or not?另外,我暂时使用此代码,但我想知道这是否是一个好习惯?

//Consider that maleRButton and femaleRButton are two radioButtons of 
//same buttonGroup
String getGender()
{
    if(maleRButton.isSelected())
    {
        return "Male";
    }
    else if(femaleRButton.isSelected())
    {
        return "Female";
    }
    else
    {
        return null;
    }
}

I tried using buttonGroup1.getSelection().getActionCommand()我尝试使用 buttonGroup1.getSelection().getActionCommand()

That approach will work, but for some reason it looks like you manually need to set the action command when you create the button.这种方法可行,但由于某种原因,您似乎需要在创建按钮时手动设置操作命令。 For example:例如:

JRadioButton maleButton = new JRadioButton( "Male" );
maleButton.setActionCommand( maleButton.getText() );

This acutally seems like a bit of a bug to me since usually the action command defaults to the text if the action command is not set.这对我来说似乎有点错误,因为如果未设置操作命令,通常操作命令默认为文本。

If you have several buttons you probably should do it this way :如果你有几个按钮,你可能应该这样做:

String getSelectedButton()
{  
    for (Enumeration<AbstractButton> buttons = buttonGroup1.getElements(); buttons.hasMoreElements();) {
        AbstractButton button = buttons.nextElement();
        if (button.isSelected()) {
                return button.getText();
        }
    }
    return null;
}

String gender=group.getSelection().getActionCommand();

它会工作,但它显示空值。

int selectedRadioButtonID = radio_group.getCheckedRadioButtonId();
// If nothing is selected from Radio Group, then it return -1
if (selectedRadioButtonID != -1) {
RadioButton selectedRadioButton = findViewById(selectedRadioButtonID);
String selectedRadioButtonText = selectedRadioButton.getText().toString();
answerList.add(selectedRadioButtonText);
} else {
Toast.makeText(this, "select radio button", Toast.LENGTH_SHORT).show();
                return false;
}

For Deatils, check this 对于细节,检查这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM