2017-10-19 78 views
0

如何獲取我的簡單單選按鈕測驗的值到新的XML佈局頁面。我不確定發生了什麼事。當我點擊按鈕時,它強制關閉。獲取RadioButton的值

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); 
} 
+0

請在崩潰時發佈logcat – Lal

回答

1

您似乎沒有初始化hasil TextView。 通過用適當的ID替換HASIL_ID,在OnCreate方法中添加以下行。

hasil = (TextView) findViewById(R.id.HASIL_ID); 
1

您應該添加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; 
      } 

我假設你已經將無線電按鈕放在無線電組內。