安卓导航: Access NavHostFragment from same Fragment

标签 android android-navigation

目前我有以下场景:用户必须登录才能使用该应用程序。这意味着我使用了 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.setOnNavigationItemSelectedListenerHomeFragement.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/

相关文章:

java - 尝试将 Assets 文件夹中找到的数据库复制到应用程序的数据库文件夹中时遇到的问题

android - 使用 Android Navigation 将数据传回上一个 fragment

Android EditText真实内容高度

android - 构建房间期间出现 StackOverflowError

android - 如何对齐抽屉导航菜单中的开关?

android - 我应该使用 'hardware' 将 NFC 数据写入空标签吗?

android - 主/细节流或抽屉导航?哪个更适合显示有关列表项的详细数据?

android - 禁用 ActionBarDrawerToggle 抽屉指示器,但保留汉堡包图标

android - 2 ViewPager 在 Android 2.3 中不滚动

android - fragment 转换在 Jetpack 导航框架中不起作用