首页 > 解决方案 > 使用 TextRange 时,文本选择在基本 TextField 中不起作用

问题描述

当文本字段显示在屏幕上时,我想选择文本字段中的所有字符。当传递像 TextRange(2,2) 这样的相同索引时,它可以正常工作,但是当使用像 TextRange(0, name.length)) 这样的不同索引时,选择不起作用。我已经提到了下面的功能

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

标签: androidandroid-jetpack-compose

解决方案


选择颜色取决于您的主题primarybackground颜色。您可以在内部使用的源代码中看到它。rememberTextSelectionColors

因此,如果您看不到选择,那可能是因为您的主题。

在此答案中查看如何在不修改主题的情况下覆盖此值。要使其适用于整个应用程序,您可以将其嵌入CompositionLocalProvider到您的主题中,如下所示:

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

推荐阅读