我正在使用导航组件作为底部导航组件。
bottomNavbar.setupWithNavController(navController)
现在工作正常,但是当我点击后退按钮时,它返回主页,但图标没有改变,它卡在上一个选定的片段中。我有三个片段,并且我在所有这些片段中分别实现了导航栏,这是这三个片段的代码。
设置片段
val bottomNavbar = view.findViewById<BottomNavigationView>(R.id.bottomNavbar)
bottomNavbar.setupWithNavController(navController)
搜索片段
val bottomNavbar = view.findViewById<BottomNavigationView>(R.id.bottomNavbarSearch)
bottomNavbar.setupWithNavController(navController)
聊天片段
val bottomNavbar = view.findViewById<BottomNavigationView>(R.id.bottomNavbar)
bottomNavbar.setupWithNavController(navController)
这里的搜索片段是我的主页片段。
我的实现中是否有错误,或者我应该切换到实现底部导航视图的旧方法。
任何帮助表示赞赏。谢谢
确保底部导航视图菜单中具有相同的 id 匹配 底部NavView片段的navGraph中对应的。
检查这个答案
您似乎已经在所有三个片段上添加了 BottomNavigationView,理想情况下,这些片段应该位于您定义了
navGraph
的片段/FragmentContainerView 下面的 Activity 视图上。
要修复此问题,您需要从所有 3 个片段中删除 BottomNavigationView,并使用以下基本结构将其添加到 Activity 上。
活动 XML 结构:
<constriantLayout>
<fragment/> //with navGraph
<bottomNavigationView/>
</constraintLayout>
Activity的onCreate使用设置BottomNavigationView的代码
val bottomNavbar = findViewById<BottomNavigationView>(R.id.bottomNavbar)
bottomNavbar.setupWithNavController(navController)
2024 年工作
菜单资源文件的 id 和导航图文件的目标 id 必须相同,然后在 onbackpressed 底部导航菜单项集上选择
菜单资源文件代码示例
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/draftsFragment"
android:icon="@drawable/baseline_home_filled_24"
android:title="@string/drafts" />
<item
android:id="@+id/dashboardFragment"
android:icon="@drawable/baseline_home_filled_24"
android:title="@string/dashboard" />
</menu>
示例导航的 NavGraph 文件
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/app_navigation"
app:startDestination="@id/dashboardFragment">
<fragment
android:id="@+id/dashboardFragment"
android:name="com.example.abc.ui.fragments.DashboardFragment"
android:label="DashboardFragment">
<fragment
android:id="@+id/draftsFragment"
android:name="com.example.abc.ui.fragments.DraftsFragment"
android:label="DraftsFragment" />
</navigation>