我刚刚开始学习Android开发,这是我遇到的障碍。
尽管使用savedInstanceState
,但每次更改屏幕方向时,都会丢失活动,并会创建新活动。这是代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
checkAnswer(true);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
checkAnswer(false);
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1)%(mQuestionBank.length);
updateQuestion();
}
});
mPreviousButton = (Button)findViewById(R.id.prev_button);
mPreviousButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
mCurrentIndex = (mCurrentIndex + mQuestionBank.length - 1)%(mQuestionBank.length);
updateQuestion();
}
});
updateQuestion();
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX);
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
}
我在onCreate函数之外创建了private static final String KEY_INDEX = "index";
。
我搞砸了哪里?另外,我想尝试在没有onRestoreInstanceState
的情况下无缘无故地做,但只是尽可能地学习。
答案 0 :(得分:0)
saveInstanceState不会阻止活动的破坏,它只允许您在onRestoreInstanceState中恢复它。如果你想完全停止这种行为,添加android:configChanges =" orientation"到你的清单。