HarmonyOS鸿蒙Next中如何解决RichText设置backgroundColor无效的问题

HarmonyOS鸿蒙Next中如何解决RichText设置backgroundColor无效的问题

【问题现象】

在深色模式下,RichText组件通过backgroundColor属性设置背景颜色不生效。

【背景知识】

【解决方案】

RichText组件不支持设置backgroundColor属性,所以当系统切换到深色模式后未生效,如果有较多的自定义HTML显示效果的场景,推荐使用Web组件。

但是对于一些简单场景如通过加载与显示一段HTML字符串,可以通过设置支持的style标签来定义RichText组件内要显示的内容样式,如:

<style>*{ background-color: red;width:100%;padding:0;font-size:50px}</style>

采用RichText组件加载后,如果有宽度或者黑边问题,可以在style里设置width和padding。示例代码如下:

import { ConfigurationConstant } from '@kit.AbilityKit';

@Entry
@Component
struct ToggleExample {
  @State isOn: boolean = false
  // 背景颜色,通过内容中添加style样式,内容添加背景颜色或者其他样式信息
  richBgContent: string = '<style>*{ background-color: red;width:100%;padding:0;font-size:50px}</style>'
  // 文字内容
  richContent: string =
    '<p style="background-color: red"><span></span><span style="white-space: pre-wrap;">温馨提示:<br/>' +
      '这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字,仅供参考。</span></p>'

  build() {
    Column() {
      RichText(this.richBgContent + this.richContent)
        .margin({ top: 28 })
        .padding(0)
        .width('100%')
        .height(150)

      Row() {
        Toggle({ type: ToggleType.Switch, isOn: this.isOn })
          .onChange(() => {
            this.isOn = !this.isOn
            // 切换深浅色主题
            let context = getContext(this).getApplicationContext()
            context.setColorMode(this.isOn ? ConfigurationConstant.ColorMode.COLOR_MODE_DARK :
            ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT)
          })
      }
    }
  }
}

浅色模式效果:

点击放大

深色模式效果:

点击放大


更多关于HarmonyOS鸿蒙Next中如何解决RichText设置backgroundColor无效的问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中如何解决RichText设置backgroundColor无效的问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


RichText组件背景颜色设置

RichText组件不支持直接设置backgroundColor属性。可以通过在HTML内容中添加style标签来定义背景颜色。示例代码如下:

import { ConfigurationConstant } from '@kit.AbilityKit';

@Entry
@Component
struct ToggleExample {
  @State isOn: boolean = false
  richBgContent: string = '<style>*{ background-color: red;width:100%;padding:0;font-size:50px}</style>'
  richContent: string =
    '<p style="background-color: red"><span></span><span style="white-space: pre-wrap;">温馨提示:<br/>' +
      '这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字,仅供参考。</span></p>'

  build() {
    Column() {
      RichText(this.richBgContent + this.richContent)
        .margin({ top: 28 })
        .padding(0)
        .width('100%')
        .height(150)

      Row() {
        Toggle({ type: ToggleType.Switch, isOn: this.isOn })
          .onChange(() => {
            this.isOn = !this.isOn
            let context = getContext(this).getApplicationContext()
            context.setColorMode(this.isOn ? ConfigurationConstant.ColorMode.COLOR_MODE_DARK :
            ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT)
          })
      }
    }
  }
}

通过这种方式可以在RichText组件中实现背景颜色的设置。

回到顶部