savedInstanceState 给了我一个错误的值

savedInstanceState gives me a wrong value

我有一个秒表应用程序,它只有一个 activity。三个按钮启动、停止、重置和一个显示计时器的文本视图。这是我的代码:

public class StopwatchActivity extends AppCompatActivity {

private int mNumberOfSeconds = 0;
private boolean mRunning = false;
private Handler handler = new Handler();
private Runnable runnable;
private TextView timeview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stopwatch);

    if (savedInstanceState != null){
        mNumberOfSeconds = savedInstanceState.getInt("number_of_second");
        mRunning = savedInstanceState.getBoolean("is_running");
        Log.e("after orient mSecond :" , String.valueOf(mNumberOfSeconds));
        Log.e("after orient mRunning :" , String.valueOf(mRunning));
        runner();
    }

}

public void onClickStart(View view){
    handler.removeCallbacks(runnable);
    mRunning = true;
    runner();
}

public void onClickStop(View view){
    mRunning = false;
    handler.removeCallbacks(runnable); 
}

public void onClickReset(View view){
    mRunning = false;
    //mNumberOfSeconds = 0;
    //timeview.setText("0:00:00");


}

public void runner(){
    timeview = (TextView) findViewById(R.id.time_view);
    runnable = new Runnable() {
        @Override
        public void run() {
            int hours = mNumberOfSeconds/3600;
            int minutes = (mNumberOfSeconds%3600)/60;
            int second = mNumberOfSeconds%60;
            String time = String.format("%d:%02d:%02d" , hours , minutes , second );
            timeview.setText(time);
            if (mRunning){
                mNumberOfSeconds++;
            }
            handler.postDelayed(this , 1000);
        }
    };
    handler.post(runnable);

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt("number_of_seconds" , mNumberOfSeconds);
    outState.putBoolean("is_running" , mRunning);
    Log.e("befor rotation second:" , String.valueOf(mNumberOfSeconds));
    Log.e("befor rotaion mrunning" , String.valueOf(mRunning));

}

我想将我的一些变量保存在 onSaveInstanceState 中,以便在方向改变后再次使用它们。正如您在代码中看到的,日志消息显示方向更改前后 mNumberOfSeconds 和 mRunning 的值。在方向更改后,mNumberOfSeconds 将给我 0 而不是我保存的值。但是 mRunning 给了我正确的价值。谁能给我任何解决方案?

以后您可以通过在 put() 和 get() 调用中使用标签来避免这种情况:

private static final String KEY_NUM_SECS = "NUM_SECS";

然后像这样使用它:

mNumberOfSeconds = savedInstanceState.getInt(KEY_NUM_SECS);

和:

outState.putInt(KEY_NUM_SECS, mNumberOfSeconds);

我对比一下你的代码,你就看得一清二楚了:

outState.putInt("number_of_seconds" , mNumberOfSeconds);
mNumberOfSeconds = savedInstanceState.getInt("number_of_second");

你用键 "number_of_seconds" 输入值,但用键 "number_of_second" 得到整数值,这是错误的地方。