IllegalStateException: Link does not have a NavController set

前端 未结 9 2246
故里飘歌
故里飘歌 2020-11-29 03:58

I\'m using Android Navigation Component for Navigation. I have a LoginFragment which has a button to transition to SignUpFragment. On clicking the button I\'m getting this e

9条回答
  •  眼角桃花
    2020-11-29 04:13

    The reason is that the fragment view isn't available inside the Activity.onCreate() method if you're adding it using FragmentContainerView (or just a FrameLayout). The proper way to get the NavController in this case is to find the NavHostFragment and get the controller from it. See the issue and the explanation.

    override fun onCreate(savedInstanceState: Bundle?) {
       ...
    
       val navHostFragment = supportFragmentManager.findFragmentById(R.id.my_fragment_container_view_id) as NavHostFragment
       val navController = navHostFragment.navController
    }
    

    Don't use instead of as some other answers suggest. See the comment from the Google team in the issue I mentioned above.

    You should always use FragmentContainerView. There are absolutely other fixes around window insets and layout issues that occur when a fragment's root layout is directly within other layouts such as ConstraintLayout, besides the underlying issues with the tag where fragments added via that tag go through lifecycle states entirely differently from the other Fragments added to the FragmentManager. The Lint check is there exactly because you absolutely should switch over to FragmentContainerView in all cases.

    There's also an announcement from AndroidDevSummit 2019 which explains why FragmentContainerView was introduced, and another thread on SO about the difference: vs as a view for a NavHost

提交回复
热议问题