我遇到了 Android 导航组件的问题。我已经在我的应用程序中设置了一个 NavHostFragment,并且我正在尝试使用 Navigation.findNavController(view).navigate() 从一个片段导航到另一个片段。但是,我不断遇到错误“View does not have a NavController set.”
如果您想仔细查看,这是该项目:https://github.com/giorgishubitidze3/fitnessApp
我在主要活动中设置的底部菜单栏图标工作得很好。但如果我尝试 从锻炼片段导航到锻炼详细信息片段应用程序崩溃并给出错误“视图没有设置导航控制器。”
我在回收器视图适配器内设置了一个点击监听器(它显示锻炼片段内的项目),如下所示:
holder.itemView.setOnClickListener{
switchToDetailCallback()
}
我尝试导航到不同的片段,如下所示:
val adapter = ExerciseAdapter(data){ ->
Navigation.findNavController(view).navigate(R.id.action_workoutsFragment_to_workoutDetails)
}
这也是主要活动 xml 的一部分,我在其中设置了片段容器视图:
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/nav_graph"
app:defaultNavHost="true"/>
尝试在chatgpt的帮助下更改内容,但仍然不起作用。
嗨,我已经在 git 上查看了代码 该错误发生在主要活动上,使用导航图时,不应替换片段以进行导航。 要导航底部栏上的顶级目的地,您可以调用
bottomNavigationBar.setupWithNavController(navController)
这将在用户点击底部导航项(即会话)时处理导航
注意:底部导航菜单项 ID 应与导航图上的片段 ID 匹配才能正常工作。您的主要活动应该如下所示
MainActivity 类:AppCompatActivity() { /* 延迟初始化导航控制器 */ private val navController: NavController by 懒惰 { val navHostFragment = supportFragmentManager .findFragmentById(R.id.fragment_container) 作为 NavHostFragment navHostFragment.navController }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bottomNavigationBar = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
val actionBar: ActionBar? = supportActionBar
actionBar?.hide()
/*
handles top level navigation between fragments
Note: menu items in bottom_navigation_menu.xml must have the same id as the fragments
* https://developer.android.com/guide/navigation/navigation-ui#bottom_navigation
*/
bottomNavigationBar.setupWithNavController(navController)
// hide bottom navigation bar when not on top level fragment
navController.addOnDestinationChangedListener { _, destination, _ ->
if (destination.id in listOf(
R.id.homeFragment,
R.id.sessionFragment,
R.id.workoutsFragment,
R.id.profileFragment
)
) {
bottomNavigationBar.visibility = View.VISIBLE
} else {
bottomNavigationBar.visibility = View.GONE
}
}
}
}
然后,从适配器回调上的锻炼片段中,您现在只需调用
findNavController().navigate(R.id.action_workoutsFragment_to_workoutDetails)
即可导航到锻炼详细信息。
参考https://developer.android.com/guide/navigation/integrations/ui?authuser=1#bottom_navigation