FragmentContainerView作为NavHostFragment

时间:2019-11-05 02:00:53

标签: android navigation fragment

似乎无法立即使用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>和AFAIK,就应该将其替换为FragmentContainerView

我丢失了什么东西还是有人可以将FragmentContainerView用作NavHostFragment

非常感谢!

5 个答案:

答案 0 :(得分:9)

2020年8月更新

这是the official Android documentation推荐的解决方案。

科特林版本:

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

Java版本:

NavHostFragment navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment);
NavController navController = navHostFragment.getNavController();

我引用了文档:

使用FragmentContainerView创建NavHostFragment时 通过手动将NavHostFragment添加到您的活动中 FragmentTransaction,尝试在其中检索NavController 通过Navigation.findNavController(Activity, @IdRes int)将失败。您应该直接检索NavController 而是从NavHostFragment。


Ove Stoerholt 报告的错误报告不会得到修复。您可以看到here的“无法修复(不可行)”状态。

答案 1 :(得分:2)

我所做的就是等待NavHostFragment扩大其观点:

科特琳:

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)
}

Java8(带有lambda):

navigationView.post(() -> { // wait for NavHostFragment to inflate
    navController = Navigation.findNavController(activity, R.id.nav_host_fragment);
    NavigationUI.setupWithNavController(navView, navController);
    navView.setNavigationItemSelectedListener(navItemSelectedListener);
});

答案 2 :(得分:1)

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

(当前)唯一的方法是:

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

答案 3 :(得分:1)

findNavController中呼叫postOnCreate,而不是onCreate

来源:https://issuetracker.google.com/issues/142847973

答案 4 :(得分:0)

使用await 42;代替android:name。有效。

class