You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Compose TextField光标置于删除线文本上时,如何保留删除线显示?

解决Jetpack Compose TextField选中时删除线消失的问题

核心原因

Compose默认的文本选中样式会替换自定义的TextDecoration,导致设置的删除线被选中状态的下划线覆盖,这是和基于View的EditText的差异点。

具体解决方案

1. 合并文本装饰样式

先通过TextDecoration.combine()把删除线和下划线合并,确保两种样式同时生效:

val mergedDecoration = TextDecoration.combine(
    listOf(TextDecoration.LineThrough, TextDecoration.Underline)
)

2. 给TextField设置自定义选中样式

在TextField的colors参数中,自定义选中状态下的文本样式,强制保留删除线:

TextField(
    value = yourText,
    onValueChange = { yourText = it },
    // 常态下仅显示删除线
    textStyle = TextStyle(textDecoration = TextDecoration.LineThrough),
    colors = TextFieldDefaults.textFieldColors(
        selectionColors = TextFieldDefaults.selectionColors(
            handleColor = Color.Blue,
            backgroundColor = Color.LightGray.copy(alpha = 0.3f),
            // 关键:选中时应用合并后的装饰样式,同时保留删除线和下划线
            selectedTextStyle = TextStyle(textDecoration = mergedDecoration)
        )
    )
)

3. BasicTextField的适配方案

如果使用BasicTextField,需要通过SelectionContainer自定义选中逻辑:

BasicTextField(
    value = yourText,
    onValueChange = { yourText = it },
    textStyle = TextStyle(textDecoration = TextDecoration.LineThrough),
    selectionContainer = {
        SelectionContainer(
            selectionColor = Color.LightGray.copy(alpha = 0.3f),
            handleColor = Color.Blue
        ) {
            Text(
                text = yourText,
                style = TextStyle(
                    textDecoration = if (LocalTextSelectionColors.current.backgroundColor != Color.Transparent) {
                        mergedDecoration
                    } else {
                        TextDecoration.LineThrough
                    }
                )
            )
        }
    }
)

关键说明

  • 必须通过TextDecoration.combine()合并样式,单独设置会被Compose的默认选中样式覆盖。
  • 自定义选中样式时,要确保selectedTextStyle包含删除线,才能在选中状态下保留原样式。

内容的提问来源于stack exchange,提问作者Vikram Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:32:10