2012-04-04 23 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; 

} 
相關問題