FragmentContainerView using findNavController

后端 未结 3 1607
日久生厌
日久生厌 2020-12-08 05:01

I\'m using Android Navigation Component with bottom navigation, lint gives a warning about replacing the tag with FragmentContainerView

相关标签:
3条回答
  • 2020-12-08 05:23

    Replace this line:

    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    

    with

    NavController navController = getNavController();
    

    Where getNavController() looks like this:

        // workaround for https://issuetracker.google.com/issues/142847973
        @NonNull
        private NavController getNavController() {
            Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
            if (!(fragment instanceof NavHostFragment)) {
                throw new IllegalStateException("Activity " + this
                        + " does not have a NavHostFragment");
            }
            return ((NavHostFragment) fragment).getNavController();
        }
    
    0 讨论(0)
  • 2020-12-08 05:26

    As per this issue, when using FragmentContainerView, you need to find the NavController using findFragmentById() rather than using findNavController() when in onCreate():

    val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
    val navController = navHostFragment.navController
    

    This is because findNavController(R.id.nav_host_fragment) relies on the Fragment's View to already be created which isn't the case when using FragmentContainerView (as it uses a FragmentTransaction under the hood to add the NavHostFragment).

    0 讨论(0)
  • 2020-12-08 05:29

    On top of the accepted answer, a little shortcut what could be used is:

    supportFragmentManager.findFragmentById(R.id.navHostMain)?.findNavController()
    

    Regards

    0 讨论(0)
提交回复
热议问题