gpt4 book ai didi

android - OnSaveInstanceState 不保存实例

转载 作者:行者123 更新时间:2023-11-30 00:30:30 25 4
gpt4 key购买 nike

我是我应用的 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();
}
}

最佳答案

让我们假设 currentIndex=2。当您旋转屏幕并重新创建 Activity 时,currentIndex 将具有保存值。这里的问题是您在创建 Activity 时设置了 2 次问题:首先在这里

int question = mQuestionBank[mCurrentIndex].getTextResId();
mTextView.setText(question);

第二次是在 onCreate 结束时(不再可见)调用 updateQuestion()。因此,值 2 最终将是 3,从而导致这种奇怪的行为。一个可能的解决方案是删除上面的第一段代码,从当前索引中减去一个,并确保将当前索引的值设置为 -1(您可能已经注意到显示的第一个问题实际上是第二个问题数组中的一个)。

关于android - OnSaveInstanceState 不保存实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44491727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com