问题
在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();
end
本文来自博客园,作者:观心静 ,转载请注明原文链接:https://www.cnblogs.com/guanxinjing/p/14776047.html
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。