Search code examples
androidandroid-fragmentsfragment

Circular navigation in navcontroller


I am having ListFragment, DetailFragment and OperationFragemnt. My ListFragment has the data list in Bundle object so it is always there when I am navigating from DetailFragment to ListFragment using

findNavController().popBackStack()

In OperationFragment my app is speaking with backend server and based on response I am trying to take user ListFragment using setFragmentResult as per the doc but can not get the setFragmentResultListener working

in OperationFragment

val resultToBeSent = "result"
parentFragmentManager.setFragmentResult("requestKey", bundleOf("bundleKey" to resultToBeSent))

in DetailFragment

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // Use the Kotlin extension in the fragment-ktx artifact
    parentFragmentManager.setFragmentResultListener("requestKey",this) { requestKey, bundle ->
   // We use a String here, but any type that can be put in a Bundle is supported
   val result = bundle.getString("bundleKey")
   // Do something with the result
   findNavController().popBackStack()
  }
}

Solution

  • The result comes from the child fragment, everything else are NavArgs (there's two directions).

    getParentFragmentManager().setFragmentResult("request_key", bundle)
    

    Not sure if .popBackStack() may interfere. I use <dialog/> and dismiss(). I mean, the result already arrives before navigating. You cannot set this as listenener unless implementing interface FragmentResultListener:

    /** Callback used to handle results passed between fragments. */
    public fun onFragmentResult(requestKey: String, result: Bundle) {
        if (requestKey.equals("request_key")) {
            result.getString("bundle_key")
        }
    }