保存/还原导航控制器状态的问题
如果在后台很长一段时间,我对活动被破坏的情况有一个问题(也可以通过不保留活动开发人员的选择来重现)。
所以,我有一个例外:
java.lang.illegalstateException:您必须在 调用getGraph()
在此代码(多个图形,这就是用于获取当前的代码)上
val myViewModel: MyViewModel = by navGraphViewModels(findNavController().graph.id) {
defaultViewModelProviderFactory
}
,该代码是为了在ongreate()块之后调用当前的代码。
然后,我通过使用此代码来实现一种机制来保存导航控制器状态:
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putBundle("nav_state", findNavController().saveState())
}
并像这样还原它:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
findNavController().restoreState(savedInstanceState?.getBundle("nav_state"))
}
由于状态未恢复,因此我再次遇到了错误。
有人有类似的问题吗?这是处理这些问题的正确方法吗?
我正在使用2.3.5。导航的版本。
I have an issue with the case when the Activity is destroyed if it's been a long time in the background (also reproducible with the don't keep Activity developer option).
So, I get an exception:
java.lang.IllegalStateException: You must call setGraph() before
calling getGraph()
on this line of code (multiple graphs, that's why .graph is used to get the current one)
val myViewModel: MyViewModel = by navGraphViewModels(findNavController().graph.id) {
defaultViewModelProviderFactory
}
which needs to be called after onCreate() blocks.
Then I implemented a mechanism to save navigation controller state by using this code:
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putBundle("nav_state", findNavController().saveState())
}
and restoring it like this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
findNavController().restoreState(savedInstanceState?.getBundle("nav_state"))
}
And I get the error again since the state is not restored.
Did anyone have an issue similar to this? Is this the right approach to handle these issues?
I'm using 2.3.5. version of the navigation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
恢复捕获块中的导航状态,如下所示,对我来说很有困难
restoring navigation state in catch block as below does the trick for me
这就是对我有用的原因:
保存
恢复NavController的NavController
,然后延迟ViewModel
That's what worked for me:
Saving the navController
Restoring the navController
And then, delay the viewModel