gpt4 book ai didi

当我在 LiveData 观察者中使用 navController 时,Android Navigation 组件图停止正常工作

转载 作者:行者123 更新时间:2023-12-05 01:19:34 24 4
gpt4 key购买 nike

我在我的演示应用程序中使用了 android 导航组件。我有一个非常简单的案例。一个 Activity ,两个 fragment ,A 和 B。我已经设置了导航控件,就像 Google 的示例应用程序一样。当我尝试使用简单的 onClickListener 从 A 打开 fragment B 时,如下所示:

val button.setOnClickListener {
val action = AFragmentDirections.openFragmentB()
findNavController().navigate(action)
}

一切正常。 B fragment 打开,并通过点击后退按钮弹出。
但是当我尝试从 LiveData 观察者使用它时,像这样:
viewModel.openFragmentB.observe(viewLifecycleOwner, Observer {
val action = AFragmentDirections.openFragmentB()
findNavController().navigate(action)
})

fragment B 打开,但通过点击后退按钮应用程序崩溃并出现错误
导航目的地 com.myapp:id/open_fragmetn_b 对此 NavController 是未知的。

为什么会发生这种情况以及如何将导航组件与 LiveData 一起使用?

最佳答案

发生此崩溃是因为当您单击后退按钮时,您的 viewmodel openFragmentB 观察者会再次收到通知,并且它正在尝试使用操作 openFragmentB 导航到 Fragment B,但此时 NavController 当前目标仍然是 Fragment B,而 Fragment B 没有有行动 openFragmentB。

有多种解决方案,一个简单的方法是在观察者内部添加检查值是否不为空,最后将 openFragmentB 值设置为空:

if(it!=null) {
val action = AFragmentDirections.openFragmentB()
findNavController().navigate(action)
viewModel.openFragmentB.value=null
}

但是为了更好的方法,您可以阅读有关 SingleLIveEvent 的信息:
https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

关于当我在 LiveData 观察者中使用 navController 时,Android Navigation 组件图停止正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53575965/

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