I can't save the previous state of my activity
This question already has an answer here:
这是你如何恢复状态:
private ImageView map;
private ImageView dot;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
map = (ImageView) findViewById(R.id.map);
dot = (ImageView) findViewById(R.id.dot);
MotionReceiver tc = new MotionReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(tc, new
IntentFilter(Constants.TEXT_MOVEMENT));
if(savedInstanceState != null){
dot.setX(savedInstanceState.getFloat("X"));
dot.setY(savedInstanceState.getFloat("Y"));
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putFloat("X", dot.getX());
savedInstanceState.putFloat("Y", dot.getY());
}
From documentation .
When your activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of that Activity instance is gone forever because the behavior indicates the activity is no longer needed. However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the instance state and is a collection of key-value pairs stored in a Bundle object.
So your problem is wrong understanding of onSavedInstanceState()
method. It's called in case, when the system destroys your app, but not you.
To save some variables, that you'll need to restore after onDestroy()
method invoke by pressing back button, you have to use SharedPreferences .
I have no clue what framework you're using, but these lines look suspect:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putFloat("X", dot.getX());
savedInstanceState.putFloat("Y", dot.getY());
}
Try:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putFloat("X", dot.getX());
savedInstanceState.putFloat("Y", dot.getY());
super.onSaveInstanceState(savedInstanceState);
}
链接地址: http://www.djcxy.com/p/26200.html
上一篇: 处理活动和布局android
下一篇: 我无法保存以前的活动状态