Pass data back to previous fragment using Android Navigation

前端 未结 4 554
天命终不由人
天命终不由人 2021-01-07 21:54

I\'ve started using Android Architecture Components (Navigation and Safe Args, View Models) along with Koin library.

Currently, I\'ve got a problem with passing argu

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 22:37

    Android just released a solution for this; Passing data between Destinations (Navigation 2.3.0-alpha02), basically, in fragment A you observe changes in a variable and in fragment B you change that value before executing popBackStack().

    Fragment A:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val navController = findNavController();
    // We use a String here, but any type that can be put in a Bundle is supported
    navController.currentBackStackEntry?.savedStateHandle?.getLiveData("key")?.observe(
        viewLifecycleOwner) { result ->
        // Do something with the result.
      }
    }
    

    Fragment B:

    navController.previousBackStackEntry?.savedStateHandle?.set("key", result)
    navController.popBackStack()
    

提交回复
热议问题