【问题标题】:How to link Bottom Bar Menu id with the String-based Route of Component Graph?How to link Bottom Bar Menu id with the String-based Route of Component Graph?
【发布时间】:2022-12-27 23:30:58
【问题描述】:

I have the following code

        val navigation: BottomNavigationView = findViewById(R.id.navigation)
        val navController = findNavController(R.id.nav_host_fragment_activity_main)

        navController.graph = navController.createGraph(startDestination = R.id.navigation_home) {
            fragment<HomeFragment>(R.id.navigation_home) {
                label = getString(R.string.title_home)
            }
            fragment<DashboardFragment>(R.id.navigation_dashboard) {
                label = getString(R.string.title_dashboard)
            }
        }

        navigation.setupWithNavController(navController)

And the bottom Bar menu is

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
            android:id="@+id/navigation_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/title_home"/>

    <item
            android:id="@+id/navigation_dashboard"
            android:icon="@drawable/ic_dashboard_black_24dp"
            android:title="@string/title_dashboard"/>

</menu>

which works fine.

However, the createGraph complaint asked me to Use routes to create your NavGraph instead

So I change my code to the following

        val navigation: BottomNavigationView = findViewById(R.id.navigation)
        val navController = findNavController(R.id.nav_host_fragment_activity_main)

        navController.graph = navController.createGraph(startDestination = navRoutes.home) {
            fragment<HomeFragment>(navRoutes.home) {
                label = getString(R.string.title_home)
            }
            fragment<DashboardFragment>(navRoutes.dashboard) {
                label = getString(R.string.title_dashboard)
            }
        }

        navigation.setupWithNavController(navController)

where

object navRoutes {
    const val home = "home"
    const val dashboard = "dashboard"
}

This compiles fines and no more complaints in createGraph function. However, the bottom bar doesn't function anymore.

My guess is because the Menu (in XML) of the Bottom bar is not pointing to the new String-based route.

How can I link the Bottom Bar Menu with the String-base route of my Navigation Graph?

【问题讨论】:

    标签: android android-navigation-graph android-bottomnav android-bottomappbar android-components


    【解决方案1】:

    Same issue here.. It seems that we have to use the deprecated way to add fragment by id, to make it works.

    Do you find any solution ?

    Thx

    【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2022-12-27
    • 2022-12-26
    • 2023-02-25
    • 2023-02-01
    • 2022-12-02
    • 2022-12-01
    • 2022-12-01
    • 2022-12-02
    相关资源
    最近更新 更多