저는 java를 처음 사용했습니다. 화면이 회전 할 때 OnSaveInstanceState
에서 OnCreate
으로 변수를 저장하려고합니다. 저장된 값을 savedInstanceState
번들에 기록했습니다. 화면이 회전하면 OnCreate(Bundle savedInstanceState)
의 번들 값이 로그에 0으로 표시되지만 OnSaveInstanceState
의 로그에는 올바른 값으로 표시됩니다.번들 손실 값
내 활동 자바는이 로그입니다
package com.hfad.stopwatch;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class StopwatchActivity extends Activity {
private static final String TAG = StopwatchActivity.class.getSimpleName();
private int seconds;
private boolean running;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
if(savedInstanceState != null){
Log.d(TAG, "onCreate() Restoring previous state");
/* restore state */
seconds = savedInstanceState.getInt("seconds");
running = savedInstanceState.getBoolean("running");
String tmpStr = String.valueOf(seconds);
Log.d(TAG,tmpStr);
Log.d(TAG, "onCreate() ending");
} else {
Log.d(TAG, "onCreate() No saved state available");
/* initialize app */
}
runTimer();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG,"onSaveInstanceState() saving state");
savedInstanceState.putInt("Seconds", seconds);
savedInstanceState.putBoolean("running", running);
String tmpStr = String.valueOf(savedInstanceState.getInt("Seconds"));
Log.d(TAG,tmpStr);
Log.d(TAG,"onSaveInstanceState() ending");
}
//Start the stopwatch running when the start button is clicked
public void onClickStart(View view){
running = true;
}
//Stop the stopwatch running when the stop button is clicked
public void onClickStop(View view){
running = false;
}
//Start the stopwatch running when the start button is clicked
public void onClickReset(View view){
running = false;
seconds = 0;
}
private void runTimer(){
final TextView timeView = (TextView)findViewById(R.id.time_view);
final Handler handler = new Handler();
handler.post(new Runnable(){
@Override
public void run(){
int hours = seconds/3600;
int minutes = (seconds%3600)/60;
int secs = seconds%60;
String time = String.format("%d:%02d:%02d",hours,minutes,secs);
timeView.setText(time);
if(running){
seconds++;
}
handler.postDelayed(this, 1000);
}
});
}
}
입니다.
07-26 21:02:19.880 6124-6124/com.hfad.stopwatch D/StopwatchActivity: onSaveInstanceState() saving state
07-26 21:02:19.880 6124-6124/com.hfad.stopwatch D/StopwatchActivity: 11
07-26 21:02:19.880 6124-6124/com.hfad.stopwatch D/StopwatchActivity: onSaveInstanceState() ending
07-26 21:02:19.940 6124-6124/com.hfad.stopwatch D/StopwatchActivity: onCreate() Restoring previous state
07-26 21:02:19.940 6124-6124/com.hfad.stopwatch D/StopwatchActivity: 0
07-26 21:02:19.940 6124-6124/com.hfad.stopwatch D/StopwatchActivity: onCreate() ending
나는 책에서 수업을하고 있지만 설명대로 작동하지 않으며 온라인에서 해결책을 찾을 수 없습니다.
당신은 당신이 도움이 경우 승인으로 답변 중 하나를 표시해야합니다. SO의 규칙을 따르십시오. – Intern