onSaveInstanceState,后续outState.putInt语句将覆盖先前的值

时间:2018-12-27 17:22:28

标签: android

我已经编写了这个非常简单的代码。 STATE_SCORE 1STATE_SCORE_2被声明为静态最终字符串,并初始化为null;

问题是,score1总是被score2覆盖,即如果我使score1 = 5score2 = 6然后旋转屏幕,则两个输出均为6。

如果我注释掉与score2有关的任何内容,则score1正常工作,我什至将score2解析为一个字符串,因此我可以使用outState.putString()来代替,结果相同,score2覆盖score1。 我使用了Log.d下面的outState.putInt(STATE_SCORE_2, score2)来查看score1被覆盖的地方,用STATE_SCORE_1调用getInt()会显示与score2相匹配的输出... < / p>

protected void onSaveInstanceState(Bundle outState) {
    //Save the scores
    outState.putInt(STATE_SCORE_1, score1);
    outState.putInt(STATE_SCORE_2, score2);
    Log.d("score1",String.valueOf(outState.getInt(STATE_SCORE_1)));
    super.onSaveInstanceState(outState);
}

,然后在onCreate方法中;

    //restore the saved instance state if one exists
    if (savedInstanceState != null) {
        score1 = savedInstanceState.getInt(STATE_SCORE_1);
        score2 = savedInstanceState.getInt(STATE_SCORE_2);

        //Set the score text views
        mScore1Tv.setText(String.valueOf(score1));
        mScore2Tv.setText(String.valueOf(score2));
    }

0 个答案:

没有答案