简体   繁体   English

在Android中重新创建活动

[英]Recreating activities in Android

In an Android app, when you rotate the screen, onCreate() is called to paint the view and create the objects. 在Android应用程序中,旋转屏幕时,将调用onCreate()绘制视图并创建对象。 The TextView objects recover the previous texts but the ImageView objects not. TextView对象恢复以前的文本,而ImageView对象则不能。 Is there a reason for that? 有什么理由吗? any answer will help me to understand how Android works :) 任何答案都将帮助我了解Android的工作原理:)

Thank you so much, 非常感谢,

On orientation change the whole Activity is recreated. 更改方向后,将重新创建整个活动。 If you want to recover data after orientation change you can do that with onSaveInstanceState and onRestoreInstanceState. 如果要在方向更改后恢复数据,可以使用onSaveInstanceState和onRestoreInstanceState进行操作。 When you change the orientation onSaveInstanceState is called to save values in a Bundle and after the Activity is recreated onRestoreInstaceState is called to load the values from the Bundle again. 更改方向时,将调用onSaveInstanceState以将值保存在Bundle中,并且在重新创建Activity后,将调用onRestoreInstaceState再次从Bundle中加载值。 You can use this like this: 您可以这样使用:

  @Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);

    // "Value" is a tag with which you can load the String again in onRestoreInstanceState.
    savedInstanceState.putString("Value", this.stringToSave);   
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // Use the tag "Value" to load the String again.
    this.stringToSave = savedInstanceState.getString("Value"); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM