繁体   English   中英

如何使用 Jetpack Compose 显示在按钮单击时隐藏的 IconButton?

[英]How to hdisplay an IconButton that is hidden on button click using Jetpack Compose?

我的 ViewModel class 中有一个 State object,默认值为false

var menuState = mutableStateOf(false)

现在我想根据 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,
                            )
                        }
                    }
                }
            )
        }
    )
}

当应用程序启动时,此代码工作正常,因为我希望隐藏 IconButton。 现在,当我想在单击按钮时更改另一个可组合的可见性时,问题就来了:

Button(
    onClick = {
        viewModel.menuState.value = true
    }
) {
    Text(
        text = "Sign out",
        fontSize = 18.sp
    )
}

什么都没发生。 IconButton 保持隐藏状态。 如何解决这个问题?

试试这种方式:

为 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,
                    )
                }
            }
        }
    )
}

之后调用此方法:

setContent {
    Scaffold(
        topBar =  TopBar(viewModel.menuState.value)       }
    )
}
   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM