在设计应用界面时,我们常常需要对某些重要的文本进行高亮显示,以引起用户的注意。同时,在一些场景中,我们需要确保长文本能够自动换行,以适应不同的屏幕尺寸和布局需求。本文将通过两个示例,分别展示如何在 HarmonyOS 应用中实现这些功能。
【示例一】文本高亮显示
 @Entry@Componentstruct Page01 {  @State originalText: string = '混沌未分天地乱,茫茫渺渺无人见。自从盘古破鸿蒙,开辟从兹清浊辨。';  @State highlightKeyword: string = '鸿蒙'; // 需要高亮显示的关键字  @State highlightedSegments: string[] = [];
  // 分割原始文本并保留关键字  private splitAndHighlight(text: string, keyword: string): string[] {    let segments: string[] = [];    let lastMatchEnd: number = 0;    while (true) {      const matchIndex = text.indexOf(keyword, lastMatchEnd);      if (matchIndex === -1) {        segments.push(text.slice(lastMatchEnd));        break;      } else {        segments.push(text.slice(lastMatchEnd, matchIndex));        segments.push(text.slice(matchIndex, matchIndex + keyword.length));        lastMatchEnd = matchIndex + keyword.length;      }    }    return segments;  }
  // 页面即将出现时进行文本分割  aboutToAppear() {    this.highlightedSegments = this.splitAndHighlight(this.originalText, this.highlightKeyword);    console.info(`分割后的文本段落:${JSON.stringify(this.highlightedSegments)}`);  }
  build() {    Column({ space: 20 }) {      Text() {        ForEach(this.highlightedSegments, (segment: string, index: number) => {          ContainerSpan() {            ImageSpan($r('app.media.app_icon')).width(0).height(1);            Span(segment).fontSize(30)              .fontColor(segment === this.highlightKeyword ? Color.White : Color.Black)              .onClick(() => {                console.info(`高亮文本被点击:${segment}`);                console.info(`点击索引:${index}`);              });          }.textBackgroundStyle({            color: segment === this.highlightKeyword ? Color.Red : Color.Transparent          });        });      }    }.width('100%').height('100%');  }}
   复制代码
 在这个示例中,我们首先定义了一个字符串 originalText 作为原始文本,并指定了需要高亮显示的关键字 highlightKeyword。然后,我们定义了一个 splitAndHighlight 函数来分割原始文本,并将包含关键字的部分与其他部分分开。在页面加载时,我们调用这个函数来获得分割后的文本段落,并使用 Span 组件来显示文本。需要注意的是,由于 Span 组件本身不支持直接设置背景颜色(即 Span 不支持.backgroundColor(Color.Orange)),因此设置背景色需要在 Span 外部嵌套 ContainerSpan 组件,并使用 textBackgroundStyle 属性来实现。
对于需要高亮显示的关键字部分,我们通过 ContainerSpan 组件的 textBackgroundStyle 属性来改变其背景颜色,同时保持字体颜色为白色,以确保高亮效果明显。
【示例二】文本自动换行
接下来,我们来看一个文本自动换行的示例。在这个例子中,我们需要将多行文本按照一定的规则自动换行。
 @Entry@Componentstruct Page02 {  @State poemLines: string[] = [    '混沌未分天地乱,',    '茫茫渺渺无人见。',    '自从盘古破鸿蒙,',    '开辟从兹清浊辨。',  ];
  build() {    Column({ space: 10 }) {      Text('Text + Span,文本无法自动换行').backgroundColor(Color.Orange);      Text() {        ForEach(this.poemLines, (line: string) => {          Span(line);        });      }      .fontSize(20);
      Text('Flex + Text,可以实现文本换行').backgroundColor(Color.Orange);      Flex({ wrap: FlexWrap.Wrap }) {        ForEach(this.poemLines, (line: string) => {          Text(line).fontSize(20);        });      }    }    .width('100%').height('100%');  }}
   复制代码
 在这个示例中,我们定义了一个字符串数组 poemLines,其中包含了多行诗句。我们展示了两种不同的方式来显示这些诗句:一种是使用 Text 和 Span 组件直接显示,这种方式默认不会自动换行;另一种是使用 Flex 容器,并设置 wrap 属性为 FlexWrap.Wrap,这样可以使得子元素在超出容器宽度时自动换行。
【技术要点总结】
1. 文本高亮:• 使用 splitAndHighlight 函数分割文本,并标记关键字。• 使用 ContainerSpan 和 Span 组件组合实现背景高亮。• 注意 Span 不支持直接设置背景颜色,需通过 ContainerSpan 的 textBackgroundStyle 属性实现。
2. 文本换行:• 使用 Flex 容器并设置 wrap 属性为 FlexWrap.Wrap,实现自动换行。• 多行文本可以通过 ForEach 循环动态生成。
希望本文能为正在学习或开发 HarmonyOS 应用的开发者们提供有用的参考和启示。
评论