NavHost未处于活动状态时,Android导航findNavController

时间:2020-01-12 09:44:10

标签: android android-fragments kotlin navigation android-jetpack

我有一个活动FragmentContainerView。在FragmentContainerView中,我有一个NavHostFragment。我想在setupActionBarWithNavControllerNavHostFragment

class MenuNavHostFragment : Fragment() {
    private lateinit var navController: NavController

    fun setup(activity: MainActivity) {
    navController = Navigation.findNavController(activity, R.id.fragment_menu_nav_host)
    NavigationUI.setupActionBarWithNavController(activity, navController)
}

在MainActivity.kt

private lateinit var menuNavHostFragment: MenuNavHostFragment
private fun setupNavigation() {
    menuNavHostFragment = MenuNavHostFragment()
    menuNavHostFragment.setup(this)
}

fragment_menu_nav_host中:

...
tools:context=".View.MenuNavHostFragment">

<fragment
    android:id="@+id/fragment_menu_nav_host"
    android:name="androidx.navigation.fragment.NavHostFragment"
...

这将导致以下错误消息: ID未引用此活动内的视图

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bla.bla/com.bla.bla.View.MainActivity}: java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3122)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3261)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1977)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6923)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)
 Caused by: java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
    at android.app.Activity.requireViewById(Activity.java:2686)
    at androidx.core.app.ActivityCompat.requireViewById(ActivityCompat.java:363)
    at androidx.navigation.Navigation.findNavController(Navigation.java:58)
    at com.bla.bla.View.MenuNavHostFragment.setup(MenuNavHostFragment.kt:36)
    at com.bla.bla.View.MainActivity.setupNavigation(MainActivity.kt:38)

我该如何解决?

1 个答案:

答案 0 :(得分:1)

为避免此异常,必须在调用navHostFragment方法之前创建定义了Navigation.findNavController()的片段。