我创建了一个简单的应用程序。单击下一个按钮时,问题将被更改。如果屏幕旋转,我希望问题仍然保持不变。我已经通过下面的代码覆盖了 Activity 方法,protected void onSaveInstanceState(Bundle outState)
但似乎没有任何效果。
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton, mFalseButton;
private TextView mQuestionTextView;
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private Question[] mQuestionBank = new Question[]{
new Question(R.string.question_australia, true),
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
Toast.makeText(getApplication(),"not null",Toast.LENGTH_LONG).show();
}else
{
Toast.makeText(getApplication(),"null",Toast.LENGTH_LONG).show();
}
mTrueButton = (Button) findViewById(R.id.true_button);
mFalseButton = (Button) findViewById(R.id.false_button);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
ImageButton mNextButton = (ImageButton) findViewById(R.id.next_button);
ImageButton mPreviousButton = (ImageButton) findViewById(R.id.previous_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Toast.makeText(getApplication(),"onSaveInstance",Toast.LENGTH_LONG).show();
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
public void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
}