简体   繁体   English

动态更改卡片中的文本 - Jetpack Compose state

[英]dynamically change text in cards - Jetpack Compose state

New to Compose and struggling hard with more complex state cases. Compose 新手,努力应对更复杂的 state 个案例。

I cant seem to change the text dynamically in these cards, only set the text manually.我似乎无法动态更改这些卡片中的文本,只能手动设置文本。 Each button press should change the text in a box, starting left to right, leaving the next boxes empty.每次按下按钮都应更改框中的文本,从左到右开始,将下一个框留空。

What is wrong here?这里有什么问题?

UI:用户界面:

val viewModel = HomeViewModel()
val guessArray = viewModel.guessArray


@Composable
fun HomeScreen() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
    ) {
        WordGrid()
        Keyboard()
    }
}


@Composable
fun WordGrid() {
    CardRow()
}


@Composable
fun Keyboard() {
    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement     = Arrangement.SpaceEvenly) {
    MyKeyboardButton(text = "A", 35)
    MyKeyboardButton(text = "B", 35)
   }
}

@Composable
fun MyCard(text: String) {
    Card(

        modifier = Modifier
        .padding(4.dp, 8.dp)
        .height(55.dp)
        .aspectRatio(1f),
    backgroundColor = Color.White,
    border = BorderStroke(2.dp, Color.Black),
) {
    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        Text(
            text = text,
            fontSize = 20.sp,
            )
        }
    }
}

@Composable
fun CardRow() {
    guessArray.forEach { rowCards ->
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            rowCards.forEach {
                MyCard(it)
            println(it)
            }
        }
    }
}

@Composable
fun MyKeyboardButton(text: String, width: Int) {

    Button(
        onClick = {
            guessArray[viewModel.currentRow][viewModel.column] = text
            viewModel.column += 1
        },
        modifier = Modifier
            .width(width.dp)
            .height(60.dp)
            .padding(0.dp, 2.dp)
    ) {
        Text(text = text, textAlign = TextAlign.Center)
        }
    }

ViewModel:视图模型:

class HomeViewModel : ViewModel() {

var currentRow = 0
var guessArray = Array(5) { Array(6) { "" }.toMutableList() }
var column = 0
}

The grid is created, but the text is never changed.网格已创建,但文本从未更改。

To make Compose view recompose with the new value, a mutable state should be used.要使 Compose 视图使用新值重新组合,应使用可变的 state。

You're already using it with remember in your composable, but it also needs to be used in your view model for properties, which should trigger recomposition.您已经在可组合项中将它与remember一起使用,但它还需要在您的视图 model 中用于属性,这应该会触发重组。

class HomeViewModel : ViewModel() {
    var currentRow  = 0
    val guessArray = List(5) { List(6) { "" }.toMutableStateList() }
    var column = 0
}

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

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