androidandroid-layoutandroid-jetpack-composeandroid-jetpackandroid-button

Jetpack Compose: How to change color of a button border depending on if it is enabled or disabled?


Is it possible to change the color of the border .border( when it is disabled? Something like ButtonDefaults.buttonColors to make border color Color.Gray if the button is disabled and keeping background transparent.

@Composable
fun MyButton(
    modifier: Modifier = Modifier,
    title: String,
    isEnabled: Boolean = true,
    onClick: () -> Unit
) {
    Button(
        modifier = modifier
            .height(40.dp)
            .border(
                width = 1.dp,
                color = Color.Red,
                shape = RoundedCornerShape(16.dp)
            )
            .background(
                color = Color.Transparent,
                shape = RoundedCornerShape(16.dp),
            ),
        shape = RoundedCornerShape(16.dp),
        onClick = onClick,
        elevation = ButtonDefaults.elevation(
            defaultElevation = 0.dp,
            pressedElevation = 0.dp,
            hoveredElevation = 0.dp
        ),
        colors = ButtonDefaults.buttonColors(
            backgroundColor = Color.Transparent,
            disabledBackgroundColor = Color.Transparent,
            contentColor = Color.White,
            disabledContentColor = Color.Gray
        ),
        enabled = isEnabled
    ) {
        Text(text = title)
    }
}

Solution

  • Just add a condition in the color attribute in the border modifier.

    Something like:

    .border(
        width = 1.dp,
        color = if (isEnabled) Color.Red else Color.Gray,
        shape = RoundedCornerShape(16.dp)
    )