gpt4 book ai didi

android - onSaveInstanceState 在 onDestroyView 之后调用

转载 作者:搜寻专家 更新时间:2023-11-01 08:21:45 24 4
gpt4 key购买 nike

我在这里处理奇怪的 fragment 生命周期行为。

我有一个托管两个 fragment 的 Activity :CityFragment - 显示城市列表和 WeatherFragment - 显示所选城市的天气预报。

当应用程序启动时,CityFragment 会显示在屏幕上,当用户选择城市时 - WeatherFragment 通过带有后台堆栈的 supportFragmentManager 添加。然后,如果用户想要旋转屏幕,我会得到图片上的情况 enter image description here

  • 0-2 -- CitiesFragment 启动
  • 3-7 -- 用户选择城市,WeatherFragment显示在屏幕上
  • 8-18 -- 屏幕旋转

正如您在日志中看到的那样,在用户选择城市后立即为 CitiesFragment 调用 onStop 和 onDestroyView,之后的 fragment View 为空。但是当屏幕旋转时,调用 CitiesFragment onSaveInstanceState(当 View 已经被销毁时)。

这里的问题是,在将代码转换为 kotlin 并使用合成进行 View 访问之后,当我想保存 recyclerview 第一个可见元素以在之后恢复时,我在 onSaveInstanceState 中得到 NullPointerException

val firstVisiblePosition = (recycler_view_cities.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()

使用旧的 java 实现,它工作正常,因为我将 recycler_view_cities 的引用存储在 fragment 中,我可以在那里访问它。

  • 问题 1。是否应该在 onStop 和 onDestroyView 之前调用 CitiesFragment 的 onSaveInstance 状态?
  • 问题2,遇到这种情况如何处理?

最佳答案

Shouldn't onSaveInstanceState for CitiesFragment be called before onStop and onDestroyView?

不一定。来自 onSaveInstanceState() 的 fragment 文档:

This corresponds to {@link Activity#onSaveInstanceState(Bundle) Activity.onSaveInstanceState(Bundle)} and most of the discussion there applies here as well. Note however: this method may be called at any time before onDestroy(). There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.

onSaveInstanceState() 将在 Activity 关闭时被调用(用户明确关闭的情况除外)。您的 fragment 收到回调,但可以在 onDestroy 之前处于任何状态,这意味着 UI 可能已经被拆除。

how to handle this kind of situation?

检查UI是否存在于onSaveInstanceState()中:

if (fragment.getView() != null) {
// Your stuff
}

关于android - onSaveInstanceState 在 onDestroyView 之后调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50326563/

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