美文网首页
Jetpack-Navigation xxx does not

Jetpack-Navigation xxx does not

作者: 卫泽洪_70a7 | 来源:发表于2022-01-01 11:42 被阅读0次

    布局:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/my_nav_graph" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    代码:

      @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            NavController controller = Navigation.findNavController(this,R.id.fragment);
            NavigationUI.setupActionBarWithNavController(this,controller);
        }
    

    原因:
    使用 FragmentContainerView 创建 NavHostFragment,或通过 FragmentTransaction 手动将 NavHostFragment 添加到您的 Activity 时,尝试通过 Navigation.findNavController(Activity, @IdRes int) 检索 Activity 的 onCreate() 中的 NavController 将失败。

    修改方法:
    直接从 NavHostFragment 检索 NavController。

    NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
            NavController controller = navHostFragment.getNavController();
    

    相关文章

      网友评论

          本文标题:Jetpack-Navigation xxx does not

          本文链接:https://www.haomeiwen.com/subject/ghwgqrtx.html