您的位置:首页 > 移动开发 > Android开发

关于Android旋转屏幕丢失数据的新读

2014-12-12 11:58 417 查看
根据之前的经验,一直以为当Android屏幕旋转的时候会重新调用onCreate(),从而导致界面上所有的数据都会被重置,需要在Manifest中对Activity设置一个属性才能让他不重新走onCreate方法。或者很麻烦的需要在
onSaveInstanceState()
方法中保存界面所有数据,然后在onRestoreInstanceState()方法中还原数据才行。

直到今天看到这样一句话:

“By default, the system uses the
Bundle
instance
state to save information about each
View
object
in your activity layout (such as the text value entered into an
EditText
object).
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:id
attribute.“

Android系统存储和还原View的状态必须有一个唯一的ID

给EditText设置id之后,果然在旋转屏幕之后数据被自动还原了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: