Android jetpack navigation component result from dialog

后端 未结 3 681
自闭症患者
自闭症患者 2021-02-08 12:44

So far I\'m successfully able to navigate to dialogs and back using only navigation component. The problem is that, I have to do some stuff in dialog and return result to the fr

3条回答
  •  佛祖请我去吃肉
    2021-02-08 13:15

    When you use Navigation Component with dialogs, this part of code looks not so good (for me it returned nothing)

    navController.currentBackStackEntry?.savedStateHandle?.getLiveData("key")?.observe(
    viewLifecycleOwner) { result ->
    // Do something with the result.}
    

    You need to try way from official docs and it help me a lot

    This part is working for me:

     val navBackStackEntry = navController.getBackStackEntry(R.id.target_fragment_id)
    
        // Create observer and add it to the NavBackStackEntry's lifecycle
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_RESUME
                && navBackStackEntry.savedStateHandle.contains("key")
            ) {
                val result =
                    navBackStackEntry.savedStateHandle.get("key")
                // Do something with the result
    
            }
        }
        navBackStackEntry.lifecycle.addObserver(observer)
    
        // As addObserver() does not automatically remove the observer, we
        // call removeObserver() manually when the view lifecycle is destroyed
        viewLifecycleOwner.lifecycle.addObserver(LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_DESTROY) {
                navBackStackEntry.lifecycle.removeObserver(observer)
            }
        })
    

    And in your dialog:

    navController.previousBackStackEntry?.savedStateHandle?.set(
                "key",
                true
            )
    

提交回复
热议问题