[英]no recomposition (Jetpack Compose)
How can I start recomposition in my buttons?如何在我的按钮中开始重组? As far as I understand something in the list itself needs to be changed, how can I go about this?据我所知,列表中的某些内容本身需要更改,我该如何解决这个问题 go?
data class KeyData(var text: String, val size: Int, var colour: Color)
val firstRowKeyboard = listOf("Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P")
.map { text: String -> KeyData(text, 35, Color.White) }.toMutableStateList()
// I tried both ways, but nothing changes
val secondRowKeyboard = "ASDFGHJKL".toCharArray()
.map { text: Char -> KeyData(text.toString(), 35, Color.White) }.toMutableStateList()
and the trigger:和触发器:
fun checkKeyboard() {
for (i in 0..9){
val letter = firstRowKeyboard[i]
if (letter.text in yellowLetterList){
firstRowKeyboard[i] = letter.copy(colour = Color.Yellow)
}
}
}
and my composables:和我的可组合物:
@Composable
fun Keyboard() {
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
viewModel.firstRowKeyboard.forEach {
MyKeyboardButton(it.text, it.size, it.colour)
}
}
}
@Composable
fun MyKeyboardButton(text: String, width: Int, colour: Color) {
val buttonColour by remember {
mutableStateOf(colour)
}
Button(
onClick = {
viewModel.addLettersToGrid(text)
},
modifier = Modifier
.width(width.dp)
.height(60.dp)
.padding(0.dp, 2.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = buttonColour),
border = BorderStroke(2.dp, Color.LightGray)
) {
Text(text = text, textAlign = TextAlign.Center)
}
}
the colour is changing in the list, so something is working, however recomposition is never triggered.列表中的颜色正在改变,所以有些东西正在工作,但是永远不会触发重组。
If the colour of the KeyData changing isnt enough then would I need to change the text within the list?如果 KeyData 的颜色变化还不够,那么我是否需要更改列表中的文本? What is a good alternative?什么是好的选择?
You are not setting你没有设置
val buttonColour by remember {
mutableStateOf(colour)
}
other than in composition.除了组成。
Thera are few options you can take您可以选择的选项很少
First one is not that good but it still will work第一个不是很好,但它仍然可以工作
val buttonColour by remember {
mutableStateOf(colour)
}
buttonColour = colour
or或者
val buttonColour by remember(colour) {
mutableStateOf(colour)
}
And better option is to remove更好的选择是删除
val buttonColour by remember(colour) {
mutableStateOf(colour)
}
from MyKeyboardButton从我的键盘按钮
@Composable
fun MyKeyboardButton(text: String, width: Int, colour: Color) {
Button(
onClick = {
viewModel.addLettersToGrid(text)
},
modifier = Modifier
.width(width.dp)
.height(60.dp)
.padding(0.dp, 2.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = colour),
border = BorderStroke(2.dp, Color.LightGray)
) {
Text(text = text, textAlign = TextAlign.Center)
}
}
and change it to a stateless Composable since you pass color from ViewModel.并将其更改为无状态可组合项,因为您从 ViewModel 传递了颜色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.