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

Android Studio 容器内文本格式化 下拉项标题加粗失效问题

可展开列表富文本加粗失效修复

问题背景

基于Fragment实现可展开下拉列表,通过子项XML布局管理下拉项内的文本格式,目标实现子项内标题部分加粗。已在字符串资源中通过<b>标签为标题添加加粗标记,但实际运行时文本无加粗效果,初步判断为容器覆盖了字符串预设格式。

现有实现代码

Kotlin逻辑代码(ItemClass)

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    val rootView = inflater.inflate(R.layout.fragment_list, container, false)
    val parent1 = Parent(0, "Wudu")
    val childItems1 = ArrayList<Child>()
    childItems1.add(Child(parent1, 0, getString(R.string.wudu)))

    parent1.childItems.clear()
    parent1.childItems.addAll(childItems1)

字符串资源代码

<string name="wudu">
    <b>Introduction</b>
    "\n
    What is most important is to set intentions…
</string>

子项布局XML代码

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingStart="16dp"
    android:paddingTop="16dp"
    android:paddingEnd="16dp"
    android:paddingBottom="16dp"
    android:textAlignment="center"
    android:textColor="#000000"
    android:textSize="20sp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="Text" />

</androidx.constraintlayout.widget.ConstraintLayout>

问题现象

运行后目标文本未展示加粗效果,参考截图:运行效果截图

修复方案

  • 根因说明:加粗失效和容器无关,是getString()方法的默认特性导致——该方法获取带HTML标签的字符串资源时,会自动剥离所有富文本标签,仅返回纯文本内容。
  • 具体修改点:
    1. 替换字符串获取逻辑
      弃用getString()拉取带格式的文本,改用支持保留富文本格式的ContextCompat.getText()方法,对应赋值代码修改为:
      // 原代码:childItems1.add(Child(parent1, 0, getString(R.string.wudu)))
      val formattedText = ContextCompat.getText(requireContext(), R.string.wudu)
      childItems1.add(Child(parent1, 0, formattedText))
      
    2. 修正字符串资源格式错误
      当前字符串中换行符前存在无意义的双引号,运行时会直接在页面显示多余引号,删除多余引号后的正确字符串配置:
      <string name="wudu">
          <b>Introduction</b>\n
          What is most important is to set intentions…
      </string>
      
    3. 适配器赋值逻辑校验
      检查列表适配器中给TextView设置文本的逻辑,禁止对传入的富文本对象调用toString()方法,直接传入CharSequence类型的文本给setText()即可;如果修改后仍不生效,可在对应TextView的XML属性中添加android:textAllCaps="false",关闭系统默认的全大写转换(该转换会强制清除富文本格式)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 18:36:24