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

本文探讨了Android应用中屏幕旋转时View实例状态的保存机制,指出默认情况下系统会通过Bundle实例自动保存布局中每个View对象的状态,如EditText中的输入内容。文章通过设置View的唯一ID解决了数据在屏幕旋转后丢失的问题,并详细解释了如何利用此机制实现状态的自动保存与恢复。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

根据之前的经验,一直以为当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之后,果然在旋转屏幕之后数据被自动还原了。

 

原文http://blog.youkuaiyun.com/h3c4lenovo/article/details/41891921

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值