Java 获得单选按钮';s值
如何将简单单选按钮测验的值添加到新的XML布局页面中。我不知道发生了什么事。当我点击按钮时,它将强制关闭Java 获得单选按钮';s值,java,android,Java,Android,如何将简单单选按钮测验的值添加到新的XML布局页面中。我不知道发生了什么事。当我点击按钮时,它将强制关闭 TextView hasil; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnSubmit = (Button)
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。 通过用适当的ID替换HASIL_ID,在OnCreate方法中添加以下行
hasil = (TextView) findViewById(R.id.HASIL_ID);
您似乎没有初始化hasil TextView。 通过用适当的ID替换HASIL_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;
}
我假设您已将单选按钮放置在单选组中。您应该添加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;
}
我假定您已将单选按钮放置在单选组中。请在碰撞时发布日志猫请在碰撞时发布日志猫