How I can retrieve current fragment in NavHostFragment?

后端 未结 8 1317
遇见更好的自我
遇见更好的自我 2020-12-15 17:06

I tried to find a method in the new Navigation components but I didn\'t find anything about that.

I have the current destination with :

mainHostFrag         


        
8条回答
  •  粉色の甜心
    2020-12-15 17:38

    You can do something like this:

      override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
    
            val navHostFragment = supportFragmentManager.fragments.first() as? NavHostFragment
            if(navHostFragment != null) {
                val childFragments = navHostFragment.childFragmentManager.fragments
                childFragments.forEach { fragment ->
                    fragment.onActivityResult(requestCode, resultCode, data)
                }
            }
        }
    

    But for more advanced communication Listeners with callback methods registered in Fragment.onAttach() (Fragment -> Activity rather one direction communication) and SharedViewModel (bidirectional, important to have ViewModelProviders, and Lifecycle owner that is scoped to getActivity() rather)

提交回复
热议问题