如何从 CheckBox 文本中删除 Spannable?

How do I remove Spannables from CheckBox text?

我在 CompoundButton 中添加了删除线。我如何添加删除线的要点是:

fun CompoundButton.addStrikeThrough() {
    val span = SpannableString(text)
    span.setSpan(
        StrikethroughSpan(),
        0,
        text.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    text = span
}

我使用 Spannable 是因为我并不总是希望删除整个文本。 CompoundButton 实际上是一个 CheckBox,选中时会删除文本。我在 CheckBox 项目列表中使用上述方法并在 onBindViewHolder 中设置侦听器。

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val todoText = todos[position]
    holder.checkBox.apply {
        isChecked = false
        text = todoText
        setOnCheckedChangeListener { checkBox, isChecked ->
            if (isChecked) {
                checkBox.addStrikeThrough()
            } else {
                // how do I write this?
                checkBox.removeStrikeThrough()
            }
        }
    }
}

当我删除另一个项目然后将另一个项目添加到列表中时,我确实处理了视图的回收 - 让我在已回收的项目上留下删除线。

如何从复选框中删除删除线?

我尝试从 CheckBox 中获取文本并将其转换为 Spannable 和 SpannableString,以便我可以调用 removeSpan(),但文本绝不是这两个 类 中任何一个的实例。

我看过一两个差不多的问题,但是他们的回答都不行。

您可以稍微更改您的代码并获得如下内容:

fun CompoundButton.setText(buttonText: String, withStrike: Boolean) {

    text = if (withStrike) {
        val span = SpannableString(buttonText)
        span.setSpan(
                StrikethroughSpan(),
                0,
                text.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        span
    } else {
        buttonText
    }
}

在你的适配器中:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val todoText = todos[position]
    holder.checkBox.apply {
        isChecked = false
        text = todoText
        setOnCheckedChangeListener { checkBox, isChecked ->
            checkBox.setText(todoText, isChecked)
        }
    }
}