Android Navigation:从同一片段访问 NavHostFragment



目前我有以下情况:用户必须登录才能使用该应用程序。这意味着我使用了 2 个nav_graphs,一个主图用于所有内容,然后一个嵌套的主图用于登录后的视图。

登录后,应显示底部导航栏以更改主页图中的选项卡。

我有以下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>

我希望能够在底部导航视图中更改选项卡,因此我使用bottomNavigationView.setOnNavigationItemSelectedListenerHomeFragement.kt中设置此逻辑。

不幸的是,当我尝试获取home_fragment.xml中的home_nav_host_fragment时,我无法获取,因为片段中的homeNavController = findNavController()只能找到主要活动中的main_nav_host_fragment

我希望findNavController()返回home_nav_host_fragment,但由于此方法仅搜索父导航控制器,而不是同一级别的导航控制器,因此找不到我想要的控制器。

是否有更好的结构可以解决这个问题?谢谢

这不是正确的方法。相反,您应该侦听导航事件并在登录图上隐藏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
}
}

然后,您可以按照用户登录的最佳实践仅使用单个图表。

最好将popUpTopopUpToInclusive结合使用来创建单向导航操作- 以便使用单个图形,而不是两个断开连接的图形。这只应应用于图中的前 1-2 个片段,例如。"后退"按钮无法导航回初始屏幕或登录屏幕,因为这些操作不计入"预期行为"。

<fragment
android:id="@+id/splashFragment"
android:name="com.acme.fragment.SplashFragment"
tools:layout="@layout/fragment_splash"
android:label="fragment_splash">
<action
android:id="@+id/action_splashFragment_to_loginFragment"
app:destination="@id/loginFragment"
app:popUpTo="@id/splashFragment"
app:popUpToInclusive="true"/>
</fragment>

最新更新