java - 在调用 Activity.Recreate() 之后维护我的 Activity 后台的最佳方法是什么?

标签 java c# android xamarin xamarin.android

我有一个 Activity 可以处理许多 Fragments,并且,对于 backstack 管理,我有一个自定义堆栈,我在其中管理 show/隐藏 Fragments。我的代码和导航完美无缺。

现在,我正在通过 Configuration Fragment 中的 Button 实现应用程序主题更改。为此,我使用方法 Activity.Recreate ();对于主题的变化,配置 fragment 的数据保留相同的数据,应用程序的主题完美改变,但是 fragment 的 BackStack 消失了,原因是,当按下后退时按钮,它离开应用程序,而不是将我发送回 fragment 或上一个 Activity ,从那里我访问了 Configuration Fragment

维护 Activity 后台堆栈的最佳方法是什么?这可能吗?

重要:仅当 Activity.Recreate(); 被调用时,因为如果 Activity 以任何其他方式销毁,我不想要 BackStack回来,我希望我的 Activity 干净

附加:

  • 我的应用程序的方向设置为纵向模式
  • 我的 Activity 的 launchModesingleTask,对于我正在执行的应用程序类型来说必须如此。

最佳答案

From onCreate documentation and this answer.

将以下逻辑添加到您的代码中:

public void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState == null) { 
        // savedInstanceState will be null only when creating the activity for the first time
        backstack = new BackStack(); //init your backstack
    } else {
      // there is a chance that your backstack will be already exists at this point
      // if not:
      // retrieve the backstack with savedInstanceState.getSerializable("stack")
    }
}

并且在调用 recreate()

之前更改主题时清除堆栈
// changing theme detected
bacstack.clear();
backstack = null;
recreate();

要在 Activity 的销毁 (onDestroy) 和重新创建 (onCreate) 之间保存堆栈,请使用此方法:

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    if (backstack != null) // the check isn't necessary, you can just put a null in the bundle
        outState.putSerializable("stack", backstack);
}

official guide 用于保存 UI 状态

The onSaveInstanceState method helps your activity to Survive Configuration change and System-initiated process death. link

关于java - 在调用 Activity.Recreate() 之后维护我的 Activity 后台的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55500105/

相关文章:

java - Android 调用 AsyncTask 时崩溃

java - AndroidDriver 无法解析为类型

java - 为什么 ExpectedException 在 Spring 中被弃用

java - 方法 Mockito.spy() 调用真正的方法?

c# - 如何使用数据库优先方法读取 asp.net core 中的表

c# - 如何将类型为 "Type"的变量传递给泛型参数

java - -source 1.6 不支持 lambda 表达式 [错误](使用 -source 8 或更高版本启用 lambda 表达式)

C# AES Base64 加密(字符串)

java - 如何获取 EC2 实例的 CloudWatch 指标数据

android - 删除图像文件后刷新图库?