安卓FragmentContainerView报错IllegalStateException:xx does not have a NavController set

今天使用ButtomNavigationView时build过程出现了如下错误:

java.lang.RuntimeException: 
Unable to start activity ComponentInfo{XXActivity}: 
java.lang.IllegalStateException: Activity XXActivity@198a72 does not have a NavController set on 2131230893       

说没有找到controller,但我获取controller的代码似乎没有问题

//装配BottomNavigation和fragment
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
        NavController navController = Navigation.findNavController(this,R.id.fragmentContainerView);
        AppBarConfiguration configuration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this,navController,configuration);
        NavigationUI.setupWithNavController(bottomNavigationView,navController);
    }

查阅资料发现,问题出在xml的组件FragmentContainerView上。
由于我使用了图形化开发工具,直接拖入NavHostFragment,发现xml使用的组件不是fragment而是FragmentContainerView,代码如下:

<androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/my_nav" />

问题就在这里。解决方法如下:
方法一:
修改xml文件,把FragmentContainerView改回fragment即可,修改后如下:

<fragment
        android:id="@+id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/my_nav" />

方法二:
不修改xml文件,而是使用supportFragmentManager获取navcontroller:

	//装配BottomNavigation和fragment
	BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
	NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentContainerView);
	NavController navController = navHostFragment.getNavController();
	AppBarConfiguration configuration = new AppBarConfiguration.Builder(navController.getGraph()).build();
	NavigationUI.setupActionBarWithNavController(this,navController,configuration);
	NavigationUI.setupWithNavController(bottomNavigationView,navController);

完成!

你可能感兴趣的:(Android,android,exception)