I have a string list of texts, when I click one of them I should color it in one color, currently my implementation colors all of the texts, what I'm doing wrong ?
var isPressed by remember { mutableStateOf(false) }
val buttonColor: Color by animateColorAsState(
targetValue = when (isPressed) {
true -> FreshGreen
false -> PastelPeach
},
animationSpec = tween()
)
LazyRow(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(25.dp)
) {
items(filterList) { filterName ->
Text(
text = filterName,
modifier = Modifier
.background(shape = RoundedCornerShape(24.dp), color = buttonColor)
.padding(horizontal = 16.dp, vertical = 8.dp)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null
) {
isPressed = !isPressed
onFilterClick(filterName)
}
)
}
}
CodePudding user response:
You are using the same state (isPressed
) for all the items.
As alternative to
CodePudding user response:
I modified your code, where I lowered down the animation and the pressed state so the parent composable won't suffer from its own re-composition
@Composable
fun MyScreen(
modifier: Modifier = Modifier,
filterList: SnapshotStateList<String>
) {
LazyRow(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(25.dp)
) {
items(filterList) { filterName ->
FilterText(
filterName
)
}
}
}
@Composable
fun FilterText(
filter: String
) {
var isPressed by remember { mutableStateOf(false) }
val buttonColor: Color by animateColorAsState(
targetValue = when (isPressed) {
true -> Color.Blue
false -> Color.Green
},
animationSpec = tween()
)
Text(
text = filter,
modifier = Modifier
.background(shape = RoundedCornerShape(24.dp), color = buttonColor)
.padding(horizontal = 16.dp, vertical = 8.dp)
.clickable {
isPressed = !isPressed
}
)
}