How to change TextField’s highlighted text color on Jetpack Compose?

In currently transitioning my app to Jetpack compose and I’m facing some problems to adapt my current color palette in some cases.

I have some TextInputLayout on my xml files that inherit the highlight text color from SECUNDARY color on my theme.

<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light.NoActionBar">
    ...
    <item name="colorPrimary">@color/blue</item>
    <item name="colorPrimaryVariant">@color/blue</item>
    <item name="colorSecondary">@color/red</item>
    <item name="colorSecondaryVariant">@color/red</item>
    ...
</style>

TextInputLayout with theme's secondary colour - xml

The problem is that my TextField on compose inherit the highlight text color from the PRIMARY color on MaterialTheme.

MaterialTheme(
    colors = Colors(
        primary = Color.Blue,
        ...
        secondary = Color.Red,
        ...
    ),
    content = content,
    typography = MaterialTheme.typography,
    shapes = MaterialTheme.shapes,
) {
   TextField(...)
}

TextField with theme's primary color - compose

I overrode the colors parameter on TextField but none seems to affect this colour.

Would there be a way of overriding the highlight color on compose without changing the colors on MaterialTheme? I would like to avoid that since it could cause problems on other screens that would use same theme.

Answer

The colors used for text selection by text and text field components are provided by LocalTextSelectionColors.current.

You can provide a custom TextSelectionColors using:

val customTextSelectionColors = TextSelectionColors(
    handleColor = Red,
    backgroundColor = Red.copy(alpha = 0.4f)
)

CompositionLocalProvider(LocalTextSelectionColors provides customTextSelectionColors) {
    TextField(
        value = text,
        onValueChange = { text = it },
        colors = TextFieldDefaults.textFieldColors(cursorColor = Red)
    )
}

If you want to change also the cursor color add colors = TextFieldDefaults.textFieldColors(cursorColor = Red).

enter image description here