我有一个 Activity
可以处理许多 Fragments
,并且,对于 backstack
管理,我有一个自定义堆栈,我在其中管理 show/隐藏 Fragments
。我的代码和导航完美无缺。
现在,我正在通过 Configuration Fragment
中的 Button
实现应用程序主题更改。为此,我使用方法 Activity.Recreate ();对于主题的变化,配置 fragment 的数据保留相同的数据,应用程序的主题完美改变,但是 fragment 的 BackStack 消失了,原因是,当按下后退时按钮,它离开应用程序,而不是将我发送回 fragment 或上一个 Activity ,从那里我访问了 Configuration Fragment
。
维护 Activity 后台堆栈的最佳方法是什么?这可能吗?
重要:仅当 Activity.Recreate();
被调用时,因为如果 Activity 以任何其他方式销毁,我不想要 BackStack回来,我希望我的 Activity 干净。
附加:
- 我的应用程序的方向设置为纵向模式。
- 我的 Activity 的
launchMode
是singleTask
,对于我正在执行的应用程序类型来说必须如此。
最佳答案
将以下逻辑添加到您的代码中:
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/