2

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

Gopi S
  • 523
  • 1
  • 5
  • 17
  • 1
    in my case it works: `(2,2)` place pointer after second character and `(0, name.length)` highlights whole text and it gets deleted by backspace. Try removing character, maybe selection missing color in your case? Selection handles with "copy/paste/etc" not visible like if I would open it by hard, maybe that's what are you talking about? Add string with which it doesn't work for you, it may be related. – Phil Dukhov Aug 24 '21 at 02:45
  • Thank you very much! @PhilipDukhov, you really saved my day. It was the problem with the color. I had white as the primary color. When changed the color selection rect was visible. Still I wonder why the white translucent color was not showing. – Gopi S Aug 24 '21 at 06:08

1 Answers1

2

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,
        )
    }
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220