是的,Android Jetpack Navigation Kotlin DSL 支持具有多个堆栈的底部导航。我们可以使用NavHostFragment
为每个页面设置一个独立的堆栈,并将它们添加到底部导航菜单中。
以下是一个简单的示例,其中我们使用了位于顶层的MainActivity
,以及五个不同的页面:HomeFragment
,SearchFragment
,FavoritesFragment
,SettingsFragment
和ProfileFragment
。每个页面都有自己的堆栈,因此我们可以在导航时保存和恢复每个页面的状态。
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
private lateinit var bottomNav: BottomNavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 初始化底部导航
bottomNav = findViewById(R.id.bottom_navigation)
// 初始化 NavHostFragment,并将其添加到布局中
val navHostFragment = NavHostFragment.create(R.navigation.nav_graph)
supportFragmentManager.beginTransaction()
.replace(R.id.nav_host_fragment_container, navHostFragment)
.setPrimaryNavigationFragment(navHostFragment)
.commit()
// 将 NavHostFragment 的 NavController 绑定到底部导航
navController = navHostFragment.navController
bottomNav.setupWithNavController(navController)
// 为每个导航图设置独立的堆栈
val navInflater = navController.navInflater
val graphHome = navInflater.inflate(R.navigation.nav_home)
graphHome.startDestination = R.id.homeFragment
val graphSearch = navInflater.inflate(R.navigation.nav_search)
graphSearch.startDestination = R.id.searchFragment
val graphFavorites = navInflater.inflate(R.navigation.nav_favorites)
graphFavorites.startDestination = R.id.favoritesFragment
val graphSettings = navInflater.inflate(R.navigation.nav_settings)
graphSettings.startDestination = R.id