我有一个处理许多Fragments
的Activity
,为了backstack
管理,我有一个自定义堆栈,我在其中管理显示/隐藏Fragments
。我的代码和导航工作得很好。
现在,我正在通过Configuration Fragment
中的Button
实现应用程序主题更改。为此,我正在使用方法活动.重新创建();对于主题的更改,配置片段的数据保留相同的数据,并且应用程序的主题完美更改,但片段的 BackStack 消失了,这就是为什么在按下后退按钮时,它会离开应用程序,而不是将我发送回片段或以前的活动,从那里我访问Configuration Fragment
。
维护我的活动后台堆栈的最佳方法是什么?这可能吗?
重要提示:仅当调用Activity.Recreate();
时,因为如果活动被任何其他方式销毁,我不希望返回 BackStack,我希望我的活动干净。
附加:
- 我的应用程序的方向设置为纵向模式。
- 我的活动
launchMode
是singleTask
,对于我正在执行的应用程序类型,必须如此。
从 on创建文档 和这个答案。
将以下逻辑添加到代码中:
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();
要保存活动的销毁(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);
}
官方指南 用于保存 UI 状态
onSaveInstanceState
方法可帮助您的活动生存 配置更改和系统启动的进程死亡。 链接