[英]How to hdisplay an IconButton that is hidden on button click using Jetpack Compose?
I have in my ViewModel class, a State object with the default value of false
.我的 ViewModel class 中有一个 State object,默认值为false
。
var menuState = mutableStateOf(false)
Now I want to display the IconButton according to the value of menuState
:现在我想根据 menuState 的值显示menuState
:
setContent {
Scaffold(
topBar = {
TopAppBar (
title = {
Text(
text = "MyApp",
fontSize = 18.sp
)
if (viewModel.menuState.value) { //Condition
IconButton(
onClick = {
//Do stuff
}
) {
Icon(
imageVector = Icons.Outlined.MoreVert,
contentDescription = null,
)
}
}
}
)
}
)
}
This code works fine, when the app starts, since I want the IconButton to be hidden.当应用程序启动时,此代码工作正常,因为我希望隐藏 IconButton。 Now the problem comes when I want to change the visibility from another composable on button click:现在,当我想在单击按钮时更改另一个可组合的可见性时,问题就来了:
Button(
onClick = {
viewModel.menuState.value = true
}
) {
Text(
text = "Sign out",
fontSize = 18.sp
)
}
Nothing happens.什么都没发生。 The IconButton remains hidden. IconButton 保持隐藏状态。 How to solve this?如何解决这个问题?
Try out this way:试试这种方式:
Create Composable method for TopBar and pass boolean parameter为 TopBar 创建 Composable 方法并传递 boolean 参数
@Composable
fun TopBar(isVisible: Boolean) {
TopAppBar (
title = {
Text(
text = "MyApp",
fontSize = 18.sp
)
if (isVisible) { //Condition
IconButton(
onClick = {
//Do stuff
}
) {
Icon(
imageVector = Icons.Outlined.MoreVert,
contentDescription = null,
)
}
}
}
)
}
After that call this method:之后调用此方法:
setContent {
Scaffold(
topBar = TopBar(viewModel.menuState.value) }
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.