HarmonyOS Text部分文字高亮设置

设置根据Text设置如下高亮代码之后,文本无法显示了, 显示空白;

import { Constants } from '../constants/LoginConstants';

/**
 * Component of privacy statement and help.
 */
@Component
export struct PrivacyStatementView {

  protocolString: string = "《用户服务协议》"
  privacyString: string = "《隐私政策》"
  allItemString: string = "我已阅读并同意"+this.protocolString+"和"+this.privacyString
  mutableStyledString: MutableStyledString = new MutableStyledString(this.allItemString, [{
    start: this.allItemString.indexOf(this.protocolString), length: this.protocolString.length,
    styledKey: StyledStringKey.FONT, styledValue: new TextStyle({ fontColor: Color.Blue })
  }, {
    start: this.allItemString.indexOf(this.privacyString), length: this.privacyString.length,
    styledKey: StyledStringKey.FONT, styledValue: new TextStyle({ fontColor: Color.Blue })
  }]);
  controller: TextController = new TextController();

  aboutToAppear():void {
    console.log(this.allItemString);
    this.controller.setStyledString(this.mutableStyledString)
  }

  build() {
    Flex({
      direction: FlexDirection.Row,
      justifyContent: FlexAlign.Start
    }) {
      Toggle({ type: ToggleType.Checkbox, isOn: false })
        .size({ width: 20, height: 20 })
        .selectedColor('#007DFF')
        .onChange((isOn: boolean) => {
          console.info('Component status:' + isOn)
        })

      Text(undefined, { controller: this.controller }).key("mutableStyledString")
      // .fontSize(12).fontColor("#FF999999")
      // .textAlign(TextAlign.Start)
    }
    .width(Constants.FULL_SCREEN)
  }
}
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

部分文字实现高亮请参考demo

export enum SpanType {
  normal,
  hyperlink,
}
export class CustomSpan {
  public content: string | Resource
  public type: SpanType
  public event: () => void
  constructor(content: string | Resource, type: SpanType = SpanType.normal, event: () => void = () => {
  }) {
    this.content = content
    this.type = type
    this.event = event
  }

  normal(): CustomSpan {
    this.type = SpanType.normal
    return this
  }

  hyperlink(event: () => void): CustomSpan {
    this.type = SpanType.hyperlink
    this.event = event
    return this
  }
}

export class CustomText {
  public static readonly PLACEHOLDER = new RegExp('(%[1-9]{1}[0-9]{0,}\\$s)')
  public spans: Array<CustomSpan>

  constructor(spans: Array<CustomSpan> = []) {
    this.spans = spans
  }

  append(span: CustomSpan): CustomText {
    this.spans.push(span)
    return this
  }

  appendNormal(text: string | Resource): CustomText {
    this.append(new CustomSpan(text).normal())
    return this
  }

  appendHyperlink(text: string | Resource, onClick: () => void): CustomText {
    this.append(new CustomSpan(text).hyperlink(onClick))
    return this
  }

  format(format: string | Resource, args: Array<CustomSpan> = []): CustomText {
    if (!format || !args || args?.length === 0) {
      this.appendNormal(format)
      return this
    }

    if (typeof format === 'string') {
      if (format.length !== 0) {
        this.resolve(format, args)
      }
    } else {
      try {
        let value: string = getContext(this).resourceManager.getStringSync(format)
        if (value && value.length !== 0) {
          this.resolve(value, args)
        }
      } catch (e) {
        console.warn(`CustomText getStringSync: ${JSON.stringify(format)} exception: ${e}`);
      }
    }
    return this
  }

  private resolve(format: string, args: Array<CustomSpan>): CustomText {
    let length: number = args.length
    format.split(CustomText.PLACEHOLDER).forEach((value: string, index: number) => {
      if (!value.match(CustomText.PLACEHOLDER)) {

        this.appendNormal(value)
        return
      }
      let argIndex: number = Number(value.replace('%', '').replace('$s', '')) - 1
      if (argIndex >= length) {
        return
      }
      let span: CustomSpan = args[argIndex++]
      if (span.type === SpanType.normal) {
        this.appendNormal(span.content)
      } else if (span.type === SpanType.hyperlink) {
        this.appendHyperlink(span.content, span.event)
      }
    })
    return this
  }
}




// TextDemoPage.ets

import { CustomSpan, CustomText, SpanType } from './TestTen';

class DeclareDemo {
  format: string | Resource = ''
  args: CustomSpan[] = []
}

@Entry
@Component
struct TextDemoPage {
  urlRegex = /测试一下/g;
  @State declare: DeclareDemo = {
    format: '',
    args: []
  }
  @State textDeclare: Array<CustomText> = []

  aboutToAppear(): void {
    let text: string = '这是一个示例文本测试一下。哈哈哈哈哈哈哈测试一下 哈哈哈哈哈测试一下'
    let urls = text.match(this.urlRegex)
    let newText: string = text
    if(urls) {
      let args: CustomSpan[] = []
      urls.forEach((url, idx) => {
        newText = newText.replace(url, `%${idx+1}$s`)
        args.push(new CustomSpan(url).hyperlink(() => {
          console.log('url: ', url)
        }),)
      });
      this.declare = {
        format: newText,
        args: args
      }

      this.textDeclare = [new CustomText().format(this.declare.format, this.declare.args)]
      console.log('this.textDeclare: ', JSON.stringify(this.textDeclare))
    }
  }

  build() {
    Row() {
      Column() {
        ForEach(this.textDeclare, (declare: CustomText, index) => {
          Text() {
            ForEach(declare.spans, (span: CustomSpan) => {
              if (span.type == SpanType.normal) {
                Span(span.content)
                  .fontSize(14)
                  .fontColor('#191919')
              } else if (span.type == SpanType.hyperlink) {
                Span(span.content)
                  .fontSize(14)
                  .fontColor('#007dff')
                  .decoration({type: TextDecorationType.None, color: '#007dff'})
                  .onClick(() => {
                    if (span.event) {
                      span.event()
                    }
                  })
              }
            })
          }
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
text怎么更改部分文字颜色
7222浏览 • 1回复 待解决
HarmonyOS 部分文高亮解决方案
41浏览 • 1回复 待解决
Text匹配文字高亮显示
856浏览 • 1回复 待解决
HarmonyOS Text组件如何设置文字方向
45浏览 • 1回复 待解决
HarmonyOS 怎么高亮显示搜索的文字
48浏览 • 1回复 待解决
HarmonyOS Text搜索关键字高亮功能
674浏览 • 1回复 待解决
HarmonyOS 如何在Text中做搜索词高亮?
343浏览 • 1回复 待解决
HarmonyOS text组件如何实现部分圆角
92浏览 • 1回复 待解决
HarmonyOS Text组件是否支持文字描边
36浏览 • 1回复 待解决