2017-10-19 8 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を初期化していないようです。 HASIL_IDを適切な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; 
      } 

ラジオボタンをラジオグループ内に配置したことを前提としています。

関連する問題