Android 如何动态更改 NavigationUI 组件中的默认选项卡

How to change dynamically default tab in NavigationUI component on Android

在我的应用程序中,我想显示底部选项卡,当单击这些选项卡时显示一个 fragment
为此,我使用 BottomNavigationViewNavigationUI 组件来显示片段

我的XML代码:

<fragment
        android:id="@+id/homePage_fragmentNavHost"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:navGraph="@navigation/home_navigator"
        app:defaultNavHost="true"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/homePage_bottomNavBar"
        app:layout_constraintTop_toBottomOf="@+id/homePage_toolbar"/>
<!--Bottom menu-->
<com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/homePage_bottomNavBar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/menu_home_navigation"
        app:labelVisibilityMode="selected"
        app:itemTextAppearanceActive="@style/BottomNavigationView.Active"
        app:itemTextAppearanceInactive="@style/BottomNavigationView"
        app:itemTextColor="@color/bottom_nav_bar_colors"
        app:itemIconTint="@color/bottom_nav_bar_colors"/>

然后我写 下面的代码 ,用于连接 NavigationUiBottomNavigationView :

private fun setupNavigation() {
    val navController = Navigation.findNavController(this, R.id.homePage_fragmentNavHost)
    NavigationUI.setupWithNavController(homePage_bottomNavBar, navController)
}

override fun onSupportNavigateUp() = Navigation.findNavController(this, R.id.homePage_fragmentNavHost).navigateUp()

但默认选项卡始终显示项目 0。

我想要写条件并检查一个值,并为此设置默认选项卡 NavigationUiBottomNavigationView

我该怎么做?

graph中你可以定义startDestination.
类似于:

    val navHostFragment = supportFragmentManager.findFragmentById(R.id.homePage_fragmentNavHost) as NavHostFragment
    val graphInflater = navHostFragment.navController.navInflater
    val navGraph = graphInflater.inflate(R.navigation.home_navigator)
    navGraph.startDestination = R.id.nav_xxxxx
    navController.graph = navGraph
            

    findViewById<BottomNavigationView>(R.id.homePage_bottomNavBar)
        .setupWithNavController(navController)