2012-04-04 131 views
1

我在一个radiogroup中有三个单选按钮。我如何告诉Java根据所选按钮做不同的事情?我有组和所有的按钮声明:如何检查选择了哪个radiogroup按钮?

final RadioGroup size = (RadioGroup)findViewById(R.id.RGSize); 
     final RadioButton small = (RadioButton)findViewById(R.id.RBS); 
     final RadioButton medium = (RadioButton)findViewById(R.id.RBM); 
     final RadioButton large = (RadioButton)findViewById(R.id.RBL); 

我知道我会说这样的事情:

if (size.getCheckedRadioButtonId().equals(small){ 

} else{ 

} 

但等于不正确的语法...我怎么能要求它的Java按钮被选中?

+0

请看看http://www.thetekblog.com/2010/07/android-radiobutton-in-radiogroup -例/ – 2012-04-04 00:47:09

回答

1

尝试:

if (size.getCheckedRadioButtonId() == small.getId()){ 
.... 
} 
else if(size.getCheckedRadioButtonId() == medium.getId()){ 
.... 
} 
1

因为getCheckedRadioButtonId()返回一个整数,你想比较单选按钮对象的整数。你应该比较small的ID(这是R.id.RBS)和getCheckedRadioButtonId()

switch(size.getCheckedRadioButtonId()){ 
    case R.id.RBS: //your code goes here.. 
        break; 
    case R.id.RBM: //your code goes here.. 
        break; 
    case R.id.RBL: //your code goes here.. 
        break; 
} 
1
int selected = size.getCheckedRadioButtonId(); 

switch(selected){ 
case R.id.RBS: 
    break; 
case R.id.RBM: 
    break; 
case R.id.RBL: 
    break; 

} 
相关问题