Home > front end >  How to achieve a disabled look on a Text composable
How to achieve a disabled look on a Text composable

Time:11-09

I'm trying to recreate a Preferences screen in Compose but I'm not sure what's the best way to implement the disabled state of an item.

Here is an example of the disabled state:

With the old TextView I can easily use the method setEnabled(), that will take care for me to disable click listeners and change the textColor. The Text() composable doesn't seem to implement this feature so, I was wondering if there is an easy way to achieve the same result.

Ideally, I would like find an easy way to get the default disabled color or the default alpha to apply to the current text color to achieve the disabled look.

CodePudding user response:

You can use ContentAlpha.disabled.

To apply it for a bunch of views, you can provide LocalContentAlpha:

CompositionLocalProvider(
    LocalContentAlpha provides if (enabled) ContentAlpha.high else ContentAlpha.disabled,
) {
    Text("title", color = Color.DarkGray.copy(LocalContentAlpha.current))
    Text("subtitle", color = Color.LightGray.copy(LocalContentAlpha.current))
}

Note that in order for LocalContentAlpha and LocalContentColor to work, your Text color and style.color parameters should be Color.Unspecified (this is the default value). If you're specifying it directly, you can apply ContentAlpha.disabled manually:

Text(
    "your text",
    color = Color.Black.copy(alpha = ContentAlpha.disabled),
    // or if you're using colored style
    style = MaterialTheme.typography.body1.let { style ->
        style.copy(color = style.color.copy(alpha = ContentAlpha.disabled))
    },
    // or just apply alpha modifier to the view
    modifier = Modifier.alpha(ContentAlpha.disabled)
)

CodePudding user response:

I found a solution, but I'm not sure if is the best: instead of changing the color of the text, I'm changing the alpha of the entire composable using the Modifier and setting the alpha to the value defined in ContentAlpha.disabled:

val alpha = if (enabled) 1f else ContentAlpha.disabled
Text(
    modifier = Modifier
        .alpha(alpha = alpha)
        .clickable(enabled = enabled) { onClick() },
    text = "Lorem ipsum",
)
  • Related