android 无重组(Jetpack合成)

l7wslrjt  于 2022-11-27  发布在  Android
关注(0)|答案(1)|浏览(229)

我如何开始在我的按钮中重新组合?就我所知,列表中的一些东西本身需要改变,我该如何着手呢?

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()

和触发器:

fun checkKeyboard() {
    for (i in 0..9){
        val letter = firstRowKeyboard[i]
        if (letter.text in yellowLetterList){
            firstRowKeyboard[i] = letter.copy(colour = Color.Yellow)
        }
    }
}

和我的作曲:

@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)
    }
}

列表中的颜色正在改变,因此某些东西正在工作,但是从未触发重新组合。
如果改变KeyData的颜色还不够,那么我需要改变列表中的文本吗?什么是好的替代方法?

dfty9e19

dfty9e191#

您没有设置

val buttonColour by remember {
    mutableStateOf(colour)
}

而不是在成分上。
您可以选择的选项不多。
第一个不是很好,但它仍然会工作

val buttonColour by remember {
        mutableStateOf(colour)
    }

   buttonColour = colour

val buttonColour by remember(colour) {
        mutableStateOf(colour)
    }

更好的选择是

val buttonColour by remember(colour) {
        mutableStateOf(colour)
    }

从我的键盘按钮

@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)
    }
}

并将其更改为无状态Composable,因为您从ViewModel传递了颜色。

相关问题