Text Selection Not Working in Basic TextField when using TextRange

Viewed 298

I want to select all the characters in the text field when the text field is shown on the screen. When passing the same index like TextRange(2,2) it works fine but when using a different index like TextRange(0, name.length)), the selection is not working. I have mentioned the function below

@Composable
fun TestFunction(name: String) {
    var fieldValue by remember {
        mutableStateOf(TextFieldValue(name, selection = TextRange(0, name.length)))
    }

    val focusRequester by remember {
        mutableStateOf(FocusRequester())
    }

    DisposableEffect(Unit) {
        focusRequester.requestFocus()
        onDispose { }
    }

    BasicTextField(
        value = fieldValue,
        onValueChange = { fieldValue = it },
        modifier = Modifier.focusRequester(focusRequester),
    )
}

1 Answers

Selection color depends on primary and background colors from your theme. You can see it in the source code of rememberTextSelectionColors which is used internally.

So if you can't see selection, that's probably because of your theme.

Check out how you can override this value without modifying your theme in this answer. To make it work for whole app you can embed this CompositionLocalProvider to your theme, like this:

@Composable
fun AppTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) {
    val colors = if (darkTheme) {
        DarkThemeColors
    } else {
        LightThemeColors
    }

    val customTextSelectionColors = TextSelectionColors(
        handleColor = Color.Red,
        backgroundColor = Color.Red.copy(alpha = 0.4f)
    )
    MaterialTheme(
        colors = colors,
        typography = typography,
        shapes = shapes,
    ) {
        CompositionLocalProvider(
            LocalTextSelectionColors provides customTextSelectionColors,
            content = content,
        )
    }
}
Related