我在保存单选按钮和复选框的检查状态时遇到问题。如何使用 onSaveInstanceState 和 onRestoreInstanceState 保存这些元素的检查状态?
这是一个简单的测验应用程序。单击完成按钮后,会打开一个新的评分表,正确答案会变为绿色。但同时,当方向改变时,用户的选择会丢失。
这是代码:
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
answer2.setTextColor(0xAA76FF03);
answer3.setTextColor(0xAA76FF03);
answer5.setTextColor(0xAA76FF03);
answer42.setTextColor(0xAA76FF03);
answer43.setTextColor(0xAA76FF03);
answer44.setTextColor(0xAA76FF03);
answer45.setTextColor(0xAA76FF03);
}
protected void onRestoreInstanceState(Bundle savedState)
{
answer2.setTextColor(0xAA76FF03);
answer3.setTextColor(0xAA76FF03);
answer5.setTextColor(0xAA76FF03);
answer42.setTextColor(0xAA76FF03);
answer43.setTextColor(0xAA76FF03);
answer44.setTextColor(0xAA76FF03);
answer45.setTextColor(0xAA76FF03);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.html_new_page);
finishButton = (Button) findViewById(R.id.finish_button);
enterName = (EditText) findViewById(R.id.enter_name);
answer1 = (EditText) findViewById(R.id.answer_1);
answer2 = (RadioButton)findViewById(R.id.answer2) ;
answer3 = (RadioButton)findViewById(R.id.answer3);
answer5 = (RadioButton)findViewById(R.id.answer5);
answer41 = (CheckBox)findViewById(R.id.answer41);
answer42 = (CheckBox) findViewById(R.id.answer42);
answer43 = (CheckBox) findViewById(R.id.answer43);
answer44 = (CheckBox) findViewById(R.id.answer44);
answer45 = (CheckBox) findViewById(R.id.answer45);
finishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String checkAnswer1 = answer1.getText().toString();
c2 = answer2.isChecked();
c3 = answer3.isChecked();
checkAnswer41 = answer41.isChecked();
checkAnswer42 = answer42.isChecked();
checkAnswer43 = answer43.isChecked();
checkAnswer44 = answer44.isChecked();
checkAnswer45 = answer45.isChecked();
c5 = answer5.isChecked();
if ( checkAnswer1.equals("Hypertext Markup Language") || checkAnswer1.equals("HyperText Markup Language")) {
c1 = true;
answer1.setTextColor(0xAA76FF03);
}
else {
c1 = false;
}
if (checkAnswer41 == false && checkAnswer42 == true && checkAnswer43 == true && checkAnswer44 == true && checkAnswer45 == true){
c4 = true;
}
else {
c4 = false;
}
int q1 = (c1) ? 1 : 0;
int q2 = (c2) ? 1 : 0;
int q3 = (c3) ? 1 : 0;
int q4 = (c4) ? 1 : 0;
int q5 = (c5) ? 1 : 0;
int correctNumber = q1 + q2 + q3 + q4 + q5;
correct = Integer.toString(correctNumber);
Intent i = new Intent();
i.setClass(Activity1.this, ResultActivity.class);
i.putExtra("outData", enterName.getText().toString());
i.putExtra("out", correct);
startActivity(i);
}
});
};
}