HarmonyOS 如何在Text中做搜索词高亮?

搜索框中输入文字, 搜索之后服务器返回的数据包含搜索词的文字要设置成高亮展示怎么实现?

HarmonyOS
2024-10-24 13:08:20
1348浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu

可以参考此文档:

https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/ui/arkts-common-components-text-display.md/

使用span来高亮展示你所需要的文字。

class formatS { //定义为解析后的标签内容数组,str是要显示的内容,isAim为是否高亮标志  
  char: string = "";  
  isAim: boolean = false;  
}  
  
@Entry  
@Component  
struct Index {  
  @State sourceStr: string = '几点睡啊你好吗几点睡啊你好吗你好吗几点睡啊你好吗你好吗几几点睡啊点';  
  @State formatStr: formatS[] = []  
  
  processSource(str: string): formatS[] {  
    let result: formatS[] = []  
  
    const regex1 = RegExp('几点睡啊', 'g');  
    let indexList: number[] = []  
    let array: RegExpExecArray | null = null  
    while ((array = regex1.exec(str)) !== null) {  
      console.log(`start: ${array.index},Found ${array[0]}.end ${regex1.lastIndex - 1}.`);  
      indexList.push(array.index, regex1.lastIndex - 1)  
    }  
  
    let cache = ""  
    for (let index = 0; index < str.length; index++) {  
      if (!indexList.includes(index)) {  
        cache = cache + str[index]  
        if (index > indexList[indexList.length-1] && index === str.length - 1) {  
          result.push({  
            char: cache,  
            isAim: false  
          })  
        }  
      } else {  
        result.push({  
          char: cache,  
          isAim: false  
        })  
        result.push({  
          char: "几点睡啊",  
          isAim: true  
        })  
        index = index + "几点睡啊".length - 1  
        cache = ""  
      }  
    }  
  
    return result  
  }  
  
  build() {  
    Column() {  
      ForEach(this.processSource(this.sourceStr), (item: formatS) => {  
        if (item.isAim) {  
          Text(item.char).fontSize(20).fontColor(Color.Red); //对目标内容进行高亮处理  
        } else {  
          Text(item.char).fontSize(20);  
        }  
      })  
    }.width('100%').height('100%')  
  }  
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
分享
微博
QQ
微信
回复
2024-10-24 15:03:57


相关问题
HarmonyOS Text搜索关键字高亮功能
1816浏览 • 1回复 待解决
HarmonyOS 怎么高亮显示搜索的文字
921浏览 • 1回复 待解决
Text匹配文字高亮显示
1417浏览 • 1回复 待解决
HarmonyOS Text部分文字高亮设置
898浏览 • 1回复 待解决
如何数据库搜索有知道的吗?
3728浏览 • 1回复 待解决
如何识别文本的邮箱并高亮显示?
1113浏览 • 1回复 待解决
HarmonyOS Text如何增加Image
725浏览 • 1回复 待解决
HarmonyOS Text如何显示 emjo 表情?
1041浏览 • 1回复 待解决
HarmonyOS Map kitsite地点搜索
723浏览 • 1回复 待解决