关于Android旋转屏幕丢失数据的新读
2016-02-19 11:08
441 查看
根据之前的经验,一直以为当Android屏幕旋转的时候会重新调用onCreate(),从而导致界面上所有的数据都会被重置,需要在Manifest中对Activity设置一个属性才能让他不重新走onCreate方法。或者很麻烦的需要在
直到今天看到这样一句话:
“By default, the system uses the
state to save information about each
in your activity layout (such as the text value entered into an
So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables
that track the user's progress in the activity.”
默认情况下,系统会使用Bundle来保存布局中每一个View对象的实例状态(例如写进EditText中的文字)。因此当你的Activity被销毁并重建之后,你不需要写任何代码就可以实现布局状态的还原了。然而你的Activity可能有一些其他你需要存储的信息,例如保存用户当前进度的成员变量值。
看到这段我感觉很奇怪,与我的经验不符,而且新写了一个只有EditText的Demo旋转屏幕测试了一下,EditText中的文字确实会因为旋转屏幕而丢失。百思不得其解之下又看到了这句话:
“Note: In
order for the Android system to restore the state of the views in your activity, each view must have a unique ID,
supplied by the
Android系统存储和还原View的状态必须有一个唯一的ID
给EditText设置id之后,果然在旋转屏幕之后数据被自动还原了。
原文http://blog.csdn.net/h3c4lenovo/article/details/41891921
onSaveInstanceState()方法中保存界面所有数据,然后在onRestoreInstanceState()方法中还原数据才行。
直到今天看到这样一句话:
“By default, the system uses the
Bundleinstance
state to save information about each
Viewobject
in your activity layout (such as the text value entered into an
EditTextobject).
So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables
that track the user's progress in the activity.”
默认情况下,系统会使用Bundle来保存布局中每一个View对象的实例状态(例如写进EditText中的文字)。因此当你的Activity被销毁并重建之后,你不需要写任何代码就可以实现布局状态的还原了。然而你的Activity可能有一些其他你需要存储的信息,例如保存用户当前进度的成员变量值。
看到这段我感觉很奇怪,与我的经验不符,而且新写了一个只有EditText的Demo旋转屏幕测试了一下,EditText中的文字确实会因为旋转屏幕而丢失。百思不得其解之下又看到了这句话:
“Note: In
order for the Android system to restore the state of the views in your activity, each view must have a unique ID,
supplied by the
android:idattribute.“
Android系统存储和还原View的状态必须有一个唯一的ID
给EditText设置id之后,果然在旋转屏幕之后数据被自动还原了。
原文http://blog.csdn.net/h3c4lenovo/article/details/41891921
相关文章推荐
- Android实现图片缓存与异步加载
- 八个最优秀的Android Studio插件
- Android SearchView 基本使用
- Android 开源框架Universal-Image-Loader完全解析(三)---源代码解读
- Android 开源框架Universal-Image-Loader完全解析(二)--- 图片缓存策略详解
- android ListView和GridView拖拽移位实现代码
- 检查Android是否具有摄像头
- Android 启动模式简析
- android客户端与javaweb服务端通信——登录小demo的启示
- android studio安装及使用
- android系统常用URI
- Android开发中PopupWindow用法实例分析
- Android省市区三级联动滚轮选择(真实项目中提取出来的组件)
- Android GridView自适应高度
- Android开发中一些被冷落但却很有用的类和方法
- Android应用中的文字字体统一设置
- Android Wi-Fi基本操作
- Android应用中去掉标题栏的方法
- android px转换dp
- android中finish()与system.exit(0)的区别?