그리고 아래처럼 분리를 하시면 코드가 눈에 더 쉽게 들어오실 겁니다.
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.foundation.layout.Column
@Composable
fun Greeting() {
var textColors by rememberSaveable { mutableStateListOf(*(0..4).map { Color.Red }.toTypedArray()) }
Column {
textColors.forEachIndexed { index, textColor ->
GreetingCard(
id = index,
text = "Hello",
textColor = textColor
) { idx ->
textColors[idx] = if (textColor == Color.Red) Color.White else Color.Red
}
}
}
}
// LazyColumn version
@Composable
fun GreetingLazy() {
var textColors by rememberSaveable { mutableStateListOf(*(0..4).map { Color.Red }.toTypedArray()) }
LazyColumn {
itemsIndexed(textColors) { index, textColor ->
GreetingCard(
id = index,
text = "Hello",
textColor = textColor
) { idx ->
textColors[idx] = if (textColor == Color.Red) Color.White else Color.Red
}
}
}
}
@Composable
fun GreetingCard(id: Int, text: String, textColor: Color, onClick: (Int) -> Unit) {
Card(modifier = Modifier.padding(15.dp)) {
Box(
modifier = Modifier
.padding(15.dp)
.clickable {
onClick(id)
}
) {
Text(
text = "Hello",
color = textColor
)
}
}
}