我是我的应用的 onSaveInstanceState 实现。我已经成功地实现了我的 onSaveInstanceState,但它在方向改变时并没有保持当前的问题。以下是我的 MainActivity。我一直在逐页关注 BigNerdRanchGuide 这本书。我不明白为什么它不起作用。
谢谢。
public class MainActivity extends AppCompatActivity {
public static final String TAG = "QuizActivity";
public static final String KEY_INDEX = "index";
private TextView mTextView;
private Button mTrueButton, mFalseButton;
private ImageButton mNext, mPrev;
private Question[] mQuestionBank = new Question[]{
new Question((R.string.pacific_ocean), true),
new Question((R.string.syria_europe), false),
new Question((R.string.canada_na), true),
new Question((R.string.africa_country), false),
new Question((R.string.china_continent), false)
};
private int mCurrentIndex = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "OnCreate(Bundle) called");
if(savedInstanceState != null){
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
mTextView = (TextView)findViewById(R.id.question);
int question = mQuestionBank[mCurrentIndex].getTextResId();
mTextView.setText(question);
...
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
outState.putInt(KEY_INDEX, mCurrentIndex);
}
private void updateQuestion() {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
int question = mQuestionBank[mCurrentIndex].getTextResId();
mTextView.setText(question);
}
private void lastQuestion(){
if (mCurrentIndex > 0){
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
int question = mQuestionBank[mCurrentIndex].getTextResId();
mTextView.setText(question);
}else{
Toast.makeText(this, "You're at the last question", Toast.LENGTH_SHORT).show();
return;
}
}
private void checkAnswer(boolean userPressedTrue){
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
int messageResId = 0;
if(userPressedTrue == answerIsTrue){
messageResId = R.string.correct;
}else{
messageResId = R.string.incorrect;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
}