问题
在Activity的onCreate生命周期里执行下列代码,导致 xxx does not have a NavController set on xxx 报错
布局:
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragment"
android:layout_width="0dp"
android:layout_height="0dp"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
app:navGraph="@navigation/snake_settings_nav"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="@id/settings"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/titleLayout" />
private NavController mController;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = SnakeActivitySettingsBinding.inflate(getLayoutInflater());
setContentView(mBinding.getRoot());
mController = Navigation.findNavController(SettingsActivity.this, R.id.fragment);
}
问题原因
问题原因就是在onCreate生命周期里FragmentContainerView对应的NavController未构建成功.
解决方法
方式一:
很简单直接onStart生命周期里获取NavController,如下代码:
@Override
protected void onStart() {
super.onStart();
mController = Navigation.findNavController(SettingsActivity.this, R.id.fragment);
}
或者,将获取NavController的任务放到view创建测绘完成后在执行
mBinding.fragment.post(new Runnable() {
@Override public void run() {
mController = Navigation.findNavController(SettingsActivity.this, R.id.fragment);
}
});
方式二:
使用getSupportFragmentManager获取
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
mController = navHostFragment.getNavController();