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

Kotlin中TextView格式化长文本时原有格式失效该如何解决?

问题解决方案

问题根本原因

Android 加载字符串资源时默认会过滤掉内置的HTML标签、将转义字符转为纯文本,直接调用setText(getString(R.string.HKCurriculum))自然无法保留加粗、斜体等格式。

修复步骤

1. 调整字符串资源定义

在原有字符串内容外层包裹<![CDATA[ ]]>标签,避免系统解析资源时自动过滤HTML标签:

<string name="HKCurriculum">
<![CDATA[
    <b>1 - 2 Cras justo odio, dapibus ac facilisis in, egestas eget quam.</b><br/><br/>
    <b>2 - 3</b>&nbsp;&nbsp;&nbsp;&nbsp;Cras justo odio, dapibus ac facilisis in, egestas eget quam.<br/>
    <b>3 - 4</b> justo odio, dapibus ac facilisis in, egestas eget quam.<br/>
    <b>4 - 5</b> justo odio, dapibus ac facilisis in, egestas eget quam.<br/>
    <b>5 - 6</b>&nbsp;&nbsp;&nbsp;&nbsp;Cras justo odio, dapibus ac facilisis in, egestas eget quam.<br/>
    <b>a - b</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Cras justo odio, dapibus ac facilisis in, egestas eget quam. <br/>
    <b>b - c</b>&nbsp;&nbsp;&nbsp;&nbsp;Cras justo odio, dapibus ac facilisis in, egestas eget quam.<br/>
    <b>y - z</b>&nbsp;&nbsp;&nbsp;&nbsp;Cras justo odio, dapibus ac facilisis in, egestas eget quam..<br/>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Cras justo odio, dapibus ac faci<br/>
    <i>Cras justo odio, dapibus ac facilisis in, egestas eget quam.</i>
]]>
</string>

你也可以保留原有的\n、\t,后续在代码中做替换,不需要手动改资源里的转义符

2. Kotlin代码中处理富文本

使用AndroidX提供的HtmlCompat将字符串转为富文本Spanned对象再设置给TextView:

import androidx.core.text.HtmlCompat

// 1. 读取字符串资源
val rawStr = getString(R.string.HKCurriculum)
// 2. 替换转义符为HTML可识别的标签(如果资源里没提前替换的话需要加这一步)
val processedStr = rawStr
    .replace("\n", "<br/>")
    .replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;")
// 3. 转为富文本对象
val richText = HtmlCompat.fromHtml(processedStr, HtmlCompat.FROM_HTML_MODE_COMPACT)
// 4. 设置给TextView
yourTextView.text = richText

注意事项

  • 如果使用DataBinding/ViewBinding,不要直接在布局XML中给android:text赋值该字符串资源,必须通过代码处理后再赋值,也可以自定义BindingAdapter统一处理富文本场景。
  • 不要使用已废弃的Html.fromHtml方法,HtmlCompat兼容所有Android主流版本,不需要额外做版本判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:15:03