FragmentContainerView作为NavHostFragment


20

好像使用FragmentContainerView开箱即用不起作用吗?

<androidx.fragment.app.FragmentContainerView
        class="androidx.navigation.fragment.NavHostFragment"
        android:id="@+id/fragment_nav_host"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_app" />

这是我使用的代码fragment-ktx:1.2.0-rc01,但总是会出现此错误:

Caused by: java.lang.IllegalStateException: Activity ...MainActivity@797467d does not have a NavController set on 2131296504

仅使用<fragment>works和AFAIK,就应该将其替换为FragmentContainerView

我是否缺少某些东西,或者有人可以FragmentContainerView用作NavHostFragment

非常感谢!

Answers:


27

由于此错误报告:https : //issuetracker.google.com/issues/142847973

(当前)唯一的方法是:

val navHostFragment = supportFragmentManager
    .findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController

(Java):

NavHostFragment navHostFragment =
    (NavHostFragment) getSupportFragmentManager()
        .findFragmentById(R.id.my_nav_host_fragment);
NavController navController = navHostFragment.getNavController();

2
肯定好用fragment而不是担心不必记住使用此替代方法?我们看到的是崩溃,但仅适用于某些用户,很奇怪……
hmac

0

我要做的是等待导航片段扩大其视图:

    super.onCreate(savedInstanceState)

    // Set up the form and list.
    setContentView(R.layout.activity_xxx)

    // Set up navigation - action bar and sidebar.
    /// Let the navigation view check/uncheck the menu items.
    nav_view.post { // wait for NavHostFragment to inflate
        val navController = findNavController()
        nav_view.setupWithNavController(navController)
        nav_view.setNavigationItemSelectedListener(this)
    }


-6

使用android:name代替class。作品。

<androidx.fragment.app.FragmentContainerView
    android:name="androidx.navigation.fragment.NavHostFragment"
    ...

即使使用android:name
Sam
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.