gpt4 book ai didi

android - 如何保存 Activity 状态

转载 作者:搜寻专家 更新时间:2023-11-01 07:37:33 26 4
gpt4 key购买 nike

我是 android 的新手。我有一个 activitymain.xml 文件。现在,我在 main.xml 文件中有一个 scroll view。当我在 portrait mode 中运行我的应用程序时,当我转到底部时 ScrollView ,当我将我的应用程序状态更改为横向模式时,比我转到 ScrollView 的顶部..这意味着当我们在之间切换时>portraitlandscape 或相反 activity 被召回。所以需要在 portrait 中保存应用程序状态并在 landscape 中恢复。那么有什么解决办法吗?提前致谢阿米尔汗一世。

最佳答案

文档在 explaining different ways to handle configuration changes 方面做得不错,包括屏幕方向变化。其中一种方法非常适合保存 UI 的临时状态,它是在 onSavedInstanceState() 方法中保存数据——正如@Jason Kuang 提到的。

通常,您可以依靠 Android 来保存和恢复 View 的状态,而无需您做任何特别的工作。 protected 方法的源代码 onSaveInstanceState() 解释(强调):

The default implementation takes care of most of the UI per-instance state for you by calling android.view.View.onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(android.os.Bundle)). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.

这有点欺骗性,因为 API 文档指出 EditTextTextView 必须有 android:freezesText="true"在布局 XML 文件中明确声明它们,以确保 Android 在调用 onSaveInstanceState() 时自动存储它们的状态。我最近没有对此进行测试,但这似乎是源代码正在做的事情。因此,最好自行处理临时 UI 状态。

另一个提示:您可以通过在 View 上调用 setSaveEnabled(false) 来明确阻止为 View 存储临时数据。 (这不会影响它的 child 。)

通常,在 onPause() 方法和 onSaveInstanceState() 中手动保存屏幕状态是个好主意。

关于android - 如何保存 Activity 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8667813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com