[英]Getting a RadioButton's value
如何將簡單單選按鈕測驗的值獲取到新的XML布局頁面。 我不確定發生了什么。 當我單擊按鈕時,它會強制關閉。
TextView hasil;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSubmit = (Button) findViewById(R.id.submit);
btnSubmit.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
int score = 0;
if (((RadioButton)findViewById(R.id.radioButton1)).isChecked()) {score++;}
if (((RadioButton)findViewById(R.id.radioButton8)).isChecked()) {score++;}
if (((RadioButton)findViewById(R.id.radioButton11)).isChecked()) {score++;}
if (((RadioButton) findViewById(R.id.radioButton16)).isChecked()){score++;}
if (((RadioButton) findViewById(R.id.radioButton19)).isChecked()){score++;}
if (((RadioButton) findViewById(R.id.radioButton24)).isChecked()){score++;}
if (((RadioButton) findViewById(R.id.radioButton25)).isChecked()){score++;}
if (((RadioButton) findViewById(R.id.radioButton29)).isChecked()){score++;}
displayResult(score);
}
});
}
private void displayResult(int score) {
String message = "You scored " + score;
message += " out of 6";
message += "\nWell done!";
hasil.setText(message);
}
您似乎沒有初始化hasil TextView。 通過將HASIL_ID替換為適當的ID,在OnCreate方法中添加以下行。
hasil = (TextView) findViewById(R.id.HASIL_ID);
您應該添加logcat消息,以便可以知道是什么原因導致您的應用崩潰。
但是,如果您想知道選中了哪個單選按鈕,則可以嘗試以下代碼。
int score=0;
RadioGroup rg = (RadioGroup)findViewById(R.id.YOUR_RADIO_GROUP_ID);
switch (rg.getCheckedRadioButtonId()) {
case R.id.radioButton1:
score++;
break;
case R.id.radioButton8:
score++;
break;
case R.id.radioButton11:
score++;
break;
case R.id.radioButton16:
score++;
break;
case R.id.radioButton19:
score++;
break;
case R.id.radioButton24:
score++;
break;
case R.id.radioButton25:
score++;
break;
case R.id.radioButton29:
score++;
break;
default:
break;
}
我假設您已將單選按鈕放置在單選組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.