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

标签 android navigation android-livedata android-architecture-navigation

我在我的演示应用程序中使用了 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/

相关文章:

android - 为 RecyclerView fragment 实现 ListAdapter

android - 即使我提供了每页加载的数据量,数据源也始终从房间数据库返回完整数据

android - Google+ 使用 Play 服务登录 6.5.87 (GoogleApiClient) - Android

java - Cocos2d中如何仅在所有操作完成后才执行函数

java - 将相对布局转换为线性布局

android - 操作栏中的向上按钮自定义

ios - 重新加载 UINavigationItem

android - 获取棉花糖中的当前位置 0,其中低于 23 API 它使用融合位置给出确切的当前位置

android-recyclerview - 如何使用来自 RecyclerView 元素的点击的导航组件?

android - 什么时候应该在android中为MVVM体系结构扩展LiveData类?