HarmonyOS 搜索结果text关键字高亮+背景如何快速实现

现在有一个需求是这样的,一个text文本中,某几个关键字需要颜色不一样而且有背景色,请问如何快速实现

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

部分文字实现高亮请参考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('111111111111---url: ', url)
        }),)
      });
      this.declare = {
        format: newText,
        args: args
      }

      this.textDeclare = [new CustomText().format(this.declare.format, this.declare.args)]
      console.log('111 -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')
                  .textBackgroundStyle({color: "#7F007DFF"})
                  .decoration({type: TextDecorationType.None, color: '#007dff'})
                  .onClick(() => {
                    if (span.event) {
                      span.event()
                    }
                  })
              }
            })
          }
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
HarmonyOS Text搜索关键字高亮功能
860浏览 • 1回复 待解决
HarmonyOS let关键字
232浏览 • 1回复 待解决
HarmonyOS 上是否有in关键字
204浏览 • 1回复 待解决
数据库入表时无法使用内建关键字
1947浏览 • 1回复 待解决
HarmonyOS 如何Text中做搜索高亮?
418浏览 • 1回复 待解决
HarmonyOS 怎么高亮显示搜索的文字
231浏览 • 1回复 待解决
Text匹配文字高亮显示
918浏览 • 1回复 待解决
HarmonyOS Text部分文字高亮设置
176浏览 • 1回复 待解决
Java Text控件,如何设置间距?
7168浏览 • 1回复 待解决
取消点击textinput时的背景高亮样式
800浏览 • 1回复 待解决
给个关键字也行
265浏览 • 1回复 待解决