Jetpack Compose State List Drawable Equivalent
Asked Answered
M

1

10

What is the best way to get functionality of a StateListDrawable in Jetpack Compose?

Mount answered 30/4, 2021 at 19:52 Comment(0)
D
13

You can use the InteractionSource to change how components appear in different states, such as when a component is pressed or dragged or focused.

Something like:

val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()

//Define the textColor, the icon and the iconTint if the field is focused or not
val textColor = if (isFocused) Color.Black else Color.Red
val icon = if (isFocused) Icons.Filled.Add else Icons.Filled.Share
val iconTint = if (isFocused) Color.Black else Color.Red

TextField(
    value = text,
    onValueChange = {text = it},
    interactionSource = interactionSource,
    leadingIcon = {Icon( icon ,"contentDescription")},
    colors = TextFieldDefaults.textFieldColors(
        textColor = textColor,
        leadingIconColor = iconTint
    ),
)

enter image description here enter image description here

or

val isPressed by interactionSource.collectIsPressedAsState()
val backgroundColor = if (isPressed) Color.Blue else Color.Red

Button(
    interactionSource = interactionSource,
    colors = ButtonDefaults.buttonColors(backgroundColor= backgroundColor),
    onClick = {}
){
    Text("Button")
}
Diapophysis answered 30/4, 2021 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.