Android Navigation findNavController 当 NavHost 不在 Activity 中



我有一个包含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)
}

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

我该如何解决这个问题?

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

相关内容

  • 没有找到相关文章

最新更新