Hassan Alhajji
Hassan Alhajji

Reputation: 43

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)
    }
}

Upvotes: 4

Views: 6489

Answers (2)

okmyan
okmyan

Reputation: 58

It would be better to use border parameter in Button function

Button(
    border = BorderStroke(
        width = 1.dp, 
        color = if (isEnabled) Color.Red else Color.Gray
    )
) { ... }

Upvotes: 1

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363369

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)
) 

Upvotes: 4

Related Questions