如何在Compose Material 3中修改TextField的光标手柄颜色?
如何修改TextField的光标手柄颜色?
TextField是基于BasicTextField封装的Material风格组件,它的文本选择样式(包括光标手柄颜色)默认由Material主题的配置控制,外层直接使用CompositionLocalProvider设置LocalTextSelectionColors会被组件内部的主题覆盖,所以无法生效。
你可以通过以下两种方式修改:
方式一:单独为某个TextField设置
直接给目标TextField的textSelectionColors参数传入自定义的TextSelectionColors实例:
val customTextSelectionColors = TextSelectionColors( handleColor = Red, backgroundColor = Red.copy(alpha = 0.4f) ) TextField( value = textValue, onValueChange = { textValue = it }, textSelectionColors = customTextSelectionColors )
方式二:全局统一修改所有TextField
如果希望应用内所有TextField都使用该样式,可以在MaterialTheme层级内配置LocalTextSelectionColors,Material组件会自动继承这个主题值:
MaterialTheme( colors = yourAppColors, typography = yourAppTypography, shapes = yourAppShapes, content = { CompositionLocalProvider( LocalTextSelectionColors provides TextSelectionColors( handleColor = Red, backgroundColor = Red.copy(alpha = 0.4f) ) ) { // 这里的所有TextField都会自动应用自定义的光标手柄颜色 YourMainAppContent() } } )
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

