简体   繁体   中英

How to get value of selected radioButton of buttonGroup

How to get value of selected radioButton ? I tried using buttonGroup1.getSelection().getActionCommand() (as posted in some of answers here) but it is not working. 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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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