Android开发 报错: xxx does not have a NavController set on xxx

Posted 观心静

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android开发 报错: xxx does not have a NavController set on xxx相关的知识,希望对你有一定的参考价值。

问题

在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

以上是关于Android开发 报错: xxx does not have a NavController set on xxx的主要内容,如果未能解决你的问题,请参考以下文章

随记--'xxx' does not contain bitcode报错

(已解决)Eclipse报错:Could not find XXX.apk. 没有Android项目命名. There is no android project named

FlinkFlink 提交任务报错 File does not exit /tmp/application_xxx-flink-conf.yml

js请求路径控制台报错 Failed to launch ‘xxx‘ because the scheme does not have a registered handler.

git 删除远程分支报错error: unable to delete ‘origin/xxx‘: remote ref does not exist

No resource identifier found for attribute ‘xxx‘ in package ‘android‘