Java 如何获取buttonGroup的选定radioButton的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25824786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get value of selected radioButton of buttonGroup
提问by Malwinder Singh
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?
如何获得 selected 的值radioButton
?我尝试使用buttonGroup1.getSelection().getActionCommand()
(如在此处的一些答案中发布的那样),但它不起作用。另外,我暂时使用此代码,但我想知道这是否是一个好习惯?
//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;
}
}
采纳答案by camickr
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.
这对我来说似乎有点错误,因为如果未设置操作命令,通常操作命令默认为文本。
回答by kartikag01
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;
}
回答by Dhawal Bhatt
String gender=group.getSelection().getActionCommand();
String gender=group.getSelection().getActionCommand();
It will work but it show null value.
它会工作,但它显示空值。
回答by Asif Ullah
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;
}