预览效果如图(网上找到demo,如有疑问请留评论蛤!):
这个是超链接
例子的数据结构如下:
new CustomMessage($r('app.media.styled_text_user_image1'), '央视新闻', '2小时前', [new CustomSpan(CustomSpanType.Normal, '【准备回家!'),new CustomSpan(CustomSpanType.Hashtag, '#神十七乘组4月30日回地球#'),new CustomSpan(CustomSpanType.Normal, '】'),new CustomSpan(CustomSpanType.Hashtag, '#神十八太空过国庆节#'),new CustomSpan(CustomSpanType.Normal, '\n按计划,在轨驻留期间,神十八乘组将迎来天舟八号货运飞船、神舟十九号载人飞船的来访,计划于今年10月下旬返回东风着陆场。\n祝一切顺利!'),new CustomSpan(CustomSpanType.Hashtag, '#神十八新闻发布会#'),new CustomSpan(CustomSpanType.Normal, '\n神十七乘组在与神十八乘组完成在轨轮换后,计划于本月30日返回东风着陆场。\n祝一切顺利!'),], $r("app.media.styled_text_user_image1")),
这是例子里的数据定义方式,和从接口里解析的json数据有所区别
再看看其他预览效果,比如有html超链接
1.超链接
未处理截图如下:
html a标签提取
const anchorRegex: RegExp = /<a[^>]+href=["']([^"']+)["'][^>]*>(.*?)<\/a>/gi;
添加点击事件,加超链接效果
public static extractHtmlAnchors(htmlStr: string): Array<HtmlHrefTxt> {const anchorRegex: RegExp = /<a[^>]+href=["']([^"']+)["'][^>]*>(.*?)<\/a>/gi;const anchors: Array<HtmlHrefTxt> = [];let matches=anchorRegex.exec(htmlStr)if (matches!== null) {// 将匹配到的href和文本内容添加到结果数组anchors.push({source:htmlStr,target:htmlStr.replace(anchorRegex, matches[2]),href: matches[1],text: matches[2]});}// 使用正则表达式替换所有匹配的<a>标签return anchors;}
UI 加载效果如下:
Text('超链接').id('TextMoreStylePageHelloWorld').titleStyle()Text() {ForEach(StringUtils.extractHtmlAnchors(LinkTextStr), (htmlHrefTxt: HtmlHrefTxt, index: number) => {ForEach(htmlHrefTxt.target.split(new RegExp(`(${htmlHrefTxt.text})`, 'gi')), (itemTxt: string, index: number) => {if (itemTxt === htmlHrefTxt.text) {TextLinkSpan({item: new CustomSpan(CustomSpanType.Normal, htmlHrefTxt.text, htmlHrefTxt.href)})} else {Span(itemTxt)}})})}.fontSize(12)
详情可查看 下面 demo 工程地址
2.文本高亮
public static stringHighLightShow(highLightStr: string, txt: string): Array<string> {let spanArray: Array<string> = []const highlightRegex: RegExp = new RegExp(`(${highLightStr})`, 'gi')spanArray = txt.split(highlightRegex)return spanArray}
3.凸显字体大小
.fontSize('秋' === txt ? 18 : 13)
4.凸显背景色-没生效

.backgroundColor(Color.Gray)
5.小结
对文本的各种操作中,大致都有正则提取成文本数组,然后根据需求装饰文本数组即可。
正则表达式虽然不难,但因为用到的地方不多,突然要写,笔者也不擅长正则碰到这样的情况也抓瞎。不过好在如今大模型 AI 很多,我一般选择 kimi 直接就能拿到所需的正则
6、demo 工程地址
Demo 工程