英文:
Make a button Unclickable from onClick
问题
我正在尝试在此代码中使用Compose和Kotlin,当计数器等于3时使按钮无法点击。 当我运行代码并且计数器可能为3时,按钮仍然可以点击,不会变为不可点击。
var counter = 0
var isClickable by remember { mutableStateOf(true) }
fun QuizScreen(modifier: androidx.compose.ui.Modifier) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
Button(enabled = isClickable, onClick = {
if (counter == 3) {
isClickable = false
}
}
}
}
尝试使用remember
变量,以便当我从onClick
中更改变量时,它会更改按钮的状态,但它仍然不会改变。
英文:
I am trying to use Compose and Kotlin in this code to make the button unclickable when counter == 3.
When I run the code and counter presumably is 3, the button stays clickable and wont change to uncklickable.
var counter = 0
var isClickable by remember { mutableStateOf(true) }
fun QuizScreen (modifier: androidx.compose.ui.Modifier) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
){
Button( enabled = isClickable,onClick = {
if(counter == 3){
isClickable = false
}
}
}
}
Tried using remember variable so when I change the variable from onClick, it changes the state of the button, but it still wont change
答案1
得分: 2
您可以使用条件 (count <3
) 来设置 enabled
参数:
var count by rememberSaveable { mutableStateOf(0) }
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
Text(text = "$count")
Button(
enabled = count <3,
onClick = { count++ }
) {
Text(text = "Count++")
}
}
在您的代码中,counter
没有被递增,它也不是一个状态,并且 Button
永远不会被重新组合。
英文:
You can use a condition (count <3
) for the enabled
parameter:
var count by rememberSaveable { mutableStateOf(0) }
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
Text(text = "$count")
Button(
enabled = count <3,
onClick = { count++ }
) {
Text(text = "Count++")
}
}
In your code counter
is not incremented and it is not a state and the Button
is never recomposed.
答案2
得分: 0
@Composable
fun QuizScreen(modifier: Modifier = Modifier) {
var count by rememberSaveable { mutableStateOf(0) }
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
Text(text = count.toString())
Button(enabled = count < 3, onClick = { count++ }) {
Text(text = "Count++")
}
}
}
英文:
@Composable
fun QuizScreen(modifier: Modifier = Modifier) {
var count by rememberSaveable { mutableStateOf(0) }
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
Text(text = count.toString())
Button( enabled = count <3,
onClick = { count++ }
) {
Text(text = "Count++")
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论