android 如何在Jetpack Compose中更改LazyColumn Onclick按钮的元素?

icomxhvb  于 2023-06-28  发布在  Android
关注(0)|答案(1)|浏览(188)

如何在Jetpack Compose中单击按钮时更改lazyColumn的元素?我想在单击“下一步”按钮时更改lazycolumn的元素。

val characters = mutableListOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z")
var randomElement = characters.random()
var randomElement2 = characters.random()
var randomElement3 = characters.random()
var randomElement4 = characters.random()
var elements = mutableListOf(randomElement, randomElement2, randomElement3, randomElement4)
@Composable
fun MyUi() {
    Column() {
        LazyColumn(content = {
            items(elements.size) { index ->
                Text(
                    text = elements[index],
                )
            }
        })
        Column() {
            Button(onClick = {
                var randomElementAnswer = characters.random()
                var randomElementAnswer2 = characters.random()
                var randomElementAnswer3 = characters.random()
                var randomElementAnswer4 = characters.random()
                elements = mutableListOf(randomElementAnswer, randomElementAnswer2, randomElementAnswer3, randomElementAnswer4)
            }) {
                Text(text = "Next")
            }
        }
    }
}
7hiiyaii

7hiiyaii1#

你必须在Jetpack Compose中使用State来存储和使用状态。

val characters = mutableListOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z")

fun getData() = List(4) { characters.random() }

@Composable
fun RandomElementsDemo() {
    var elements by remember {
        mutableStateOf(getData())
    }

    Column {
        LazyColumn {
            items(elements) {
                Text(it)
            }
        }
        Button(
            onClick = {
                elements = getData()
            },
        ) {
            Text("Next")
        }
    }
}

相关问题