目前我有以下场景:用户必须登录才能使用该应用程序。这意味着我使用了 2 个 nav_graph,一个用于所有内容的主图,然后是一个用于登录后 View 的嵌套主图。
登录后,底部导航栏应出现以更改主页图表中的选项卡。
我有以下home_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.home.HomeFragment">
<fragment
android:id="@+id/home_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/home_graph"
app:defaultNavHost="true"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
app:menu="@menu/navigation_items"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
而且我希望能够更改底部导航 View 中的选项卡,因此我使用 bottomNavigationView.setOnNavigationItemSelectedListener
在 HomeFragement.kt 中设置此逻辑。
不幸的是,当我尝试在 home_fragment.xml 中获取 home_nav_host_fragment
时,我不能,因为 fragment 中的 homeNavController = findNavController()
只能找到主 Activity 中的 main_nav_host_fragment
。
我希望 findNavController()
返回 home_nav_host_fragment
但因为此方法仅搜索父 NavController,而不是同一级别的 NavController,因此无法找到我想要的.
是否有更好的结构可以解决这个问题?谢谢
最佳答案
这不是正确的方法。相反,你应该 listen for navigation events并在登录图表上隐藏 BottomNavigationView
:
navController.addOnDestinationChangedListener { _, destination, _ ->
if(destination.parent!!.id == R.id.login_graph) {
toolbar.visibility = View.GONE
bottomNavigationView.visibility = View.GONE
} else {
toolbar.visibility = View.VISIBLE
bottomNavigationView.visibility = View.VISIBLE
}
}
然后,您可以仅使用一个图表,遵循 best practices for user login .
关于安卓导航: Access NavHostFragment from same Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57600225/