[英]Why BottomNavigation show in the next page in Jetpack Compose?
您需要指定要显示的屏幕和不想要的屏幕; 否则,它将显示在Scaffold
主体(您有bottomBar
)内的所有屏幕上。 下面的代码来自我的应用程序。
创建一个状态来观察 navController 上的任何目的地变化
在里面when
你可以放置任何你想要显示的屏幕navigationBar
NoBottomBar
否则只需将currentScreen
设置为NoBottomBar
@Composable
private fun NavController.currentScreen(): State<MainSubScreen> {
val currentScreen = remember { mutableStateOf<MainSubScreen>(MainSubScreen.Home) }
DisposableEffect(key1 = this) {
val listener = NavController.OnDestinationChangedListener { _, destination, _ ->
when {
destination.hierarchy.any { it.route == MainSubScreen.Home.route } -> {
currentScreen.value = MainSubScreen.Home
} else -> currentScreen.value = MainSubScreen.NoBottomBar
}
}
addOnDestinationChangedListener(listener)
}
return currentScreen
}
在您放置底部栏的脚手架上
所以你可以检查currentScreen
是NoBottomBar
如果是的话,不要显示它
// initialized currentScreeen above
val currentScreen by navController.currentScreen()
Scaffold(
bottomBar = {
if (currentScreen != MainSubScreen.NoBottomBar) {
MainBottomNavigation()
} else Unit
}
) {
// Your screen
}
这取决于您放置 NavHost 的位置。 如果它包裹了您的 Scaffold,那么您可以导航 Composable 覆盖整个屏幕
NavHost(
navController = navController,
startDestination = "start_destination"
) {
composable(route = "start_destination") { ->
Scaffold(){...}
}
}
如果 NavHost 在content: @Composable (PaddingValues) -> Unit
内部content: @Composable (PaddingValues) -> Unit
,当您在TopAbbpar
、 Tabs
或BottomNavigation
保持在屏幕上时导航
我喜欢一种方法来做到这一点。
尝试使用ViewModle控制BottomNavigation的可见性,进入MainPage时显示,离开MainPage时隐藏
// ViewModel
class VM: ViewModel() {
private val _state: MutableLiveData<Boolean> = MutableLiveData(true)
val state: LiveData<Boolean> get() = _state
fun setState(status: Boolean) {
_state.postValue(status)
}
}
// MainPage
@Compose MainPage(vm: VM) {
LaunchedEffect(key1 = true) {
vm.setState(true)
}
DisposableEffect(key1 = true) {
onDispose {
vm.setState(false)
}
}
}
// page contains Scaffold
@Composable
fun Greeting(vm: VM) {
// State of BottomNavigation`s visibility
val state = remember { mutableStateOf<Boolean>(true) }
// read the BottomNavigation`s visibility from ViewModel and send to State
vm.state.observeAsState().value?.let { state.value = it }
Scaffold(bottomBar = {
// show / hide BottomNavigation controlled by State
state.takeIf { it.value }?.let {
BottomNavigation {
list.forEachIndexed { index, label ->
BottomNavigationItem(
label = { Text(text = label) },
selected = index == selectedItem.value,
onClick = { selectedItem.value = index },
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_launcher_foreground),
contentDescription = null
)
})
}
}
}
}) {
NavHost(navController = navController, startDestination = "one") {
composable(route = "one") { PageList(navController, vm) }
composable(route = "detail") { PageDetail(vm) }
}
}
}
如果不想快速隐藏BottomNavigation,可以在Navigation 之前隐藏BottomNavigation。
您需要使用 2 个导航控制器,第一个用于主导航,第二个用于在底部导航中导航。 这个视频对我有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.