android - 使用 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),
)
}
解决方案
选择颜色取决于您的主题primary
和background
颜色。您可以在内部使用的源代码中看到它。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,
)
}
}
推荐阅读
- idl-programming-language - 使用 idl 的曲线下面积
- r - 将预测值添加到原始 df
- python - 如何更改 kivy Graph 的背景颜色?
- javascript - 从输入中检索数据 - laravel
- xslt - 按类型分组的 xslt 字段
- java - 如何使用 CSS 选择器在元素之间进行选择
- error-handling - 无法在 Gerrit 中加载插件事件日志
- mongodb - 在 MongoDB 中获取文档的一部分
- android - 发生内部错误。[ MISSING_CLIENT_IDENTIFIER ]
- javascript - html5 文件输入 - 如何使用 javascript 更改文件文本的颜色?