Compose LazyColumn 选择一项

时间:2021-03-25 05:56:40

标签: android android-jetpack android-jetpack-compose android-jetpack-compose-list

我想选择 LazyColumn 的一项并更改文本颜色。 如何确定选择了哪个项目?

代码:

val items = listOf(Pair("A", 1), Pair("AA", 144), Pair("BA", 99))
var selectedItem by mutableStateOf(items[0])
LazyColumn {
    this.items(items = items) {
        Row(modifier = Modifier.clickable(onClick = {selectedItem = it}) {
            if (selectedItem == it) {
                Text(it.first, color = Color.Red)
            } else {
                Text(it.first)
            }
        }
    }
}

取决于我如何保存它(记住或不记住),如果我点击一个而不只是我点击的最后一个,它们只会突出显示两者。

1 个答案:

答案 0 :(得分:1)

您可以使用 .selectable 修饰符代替 .clickable

类似于:

data class Message(val id: Int,
                   val message : String)
val messages : List<Message> = listOf(...))

val listState = rememberLazyListState()
var selectedIndex by remember{mutableStateOf(-1)}
 
LazyColumn(state = listState) {
        items(items = messages) { message ->

            Text(
                text = message.message,
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        if (message.id == selectedIndex)
                            Color.Red else Color.Yellow
                    )
                    .selectable(
                        selected = message.id == selectedIndex,
                        onClick = { if (selectedIndex != message.id)
                             selectedIndex = message.id else selectedIndex = -1})
            )
        }
 }

在您的情况下,您可以使用:

var selectedItem by remember{mutableStateOf( "")}
LazyColumn {
    this.items(items = items) {
        Row(modifier = Modifier.selectable(
            selected = selectedItem == it.first,
            onClick = { selectedItem = it.first}
                )
        ) {
            if (selectedItem == it.first) {
                Text(it.first, color = Color.Red)
            } else {
                Text(it.first)
            }
        }
    }
}