鸿蒙ArkTS文本组件全解析:从基础显示到高级富文本编辑

50 阅读4分钟

鸿蒙ArkTS文本组件全解析:从基础显示到高级富文本编辑

HarmonyOS NEXT的推出标志着鸿蒙生态进入了全新阶段,其原生语言ArkTS为应用开发带来了更强大的能力和性能优化。在应用界面开发中,文本组件是最基础也是最核心的部分。本文将深入探讨ArkTS中的文本处理技术,通过实际代码示例展示如何高效地使用各种文本组件。

一、文本组件概述

ArkTS提供了丰富而层次分明的文本处理组件体系,涵盖了从简单文本展示到复杂富文本编辑的全场景需求。这些组件设计精巧,性能优异,能够帮助开发者创建出色的文本交互体验。

// 文本组件的基础引入
import { Text, Span, TextInput, TextArea } from '@kit.ArkUI';
import { RichEditor, RichEditorController } from '@kit.ArkUI';
import { SymbolGlyph, SymbolSpan } from '@kit.ArkUI';
import { StyledString, MutableStyledString } from '@kit.ArkUI';

二、文本显示:Text与Span组件

1. Text基础使用

Text组件是最基础的文本展示组件,支持丰富的样式属性设置。

@Entry
@Component
struct BasicTextExample {
  build() {
    Column() {
      // 基础文本显示
      Text('这是一个基础文本示例')
        .fontSize(20)
        .fontColor(Color.Black)
        .fontWeight(FontWeight.Medium)
        .textAlign(TextAlign.Center)
        .margin(10)

      // 多行文本与溢出处理
      Text('这是一段非常长的文本内容,当文字超过容器宽度时会自动换行,如果设置最大行数限制,超出的部分将会被省略显示')
        .fontSize(16)
        .maxLines(2)
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .margin(10)
    }
    .width('100%')
    .padding(20)
  }
}

2. Span精细化文本控制

Span允许在同一文本段落中实现不同样式。

@Entry
@Component
struct SpanTextExample {
  build() {
    Column() {
      Text() {
        Span('红色加粗')
          .fontColor(Color.Red)
          .fontWeight(FontWeight.Bold)
          .fontSize(20)
        
        Span(' 普通文本 ')
          .fontSize(16)
        
        Span('蓝色下划线')
          .fontColor(Color.Blue)
          .decoration({ type: TextDecorationType.Underline })
          .fontSize(18)
      }
      .textAlign(TextAlign.Center)
      .margin(10)
    }
    .width('100%')
    .padding(20)
  }
}

三、文本输入:TextInput与TextArea

1. TextInput单行输入

@Entry
@Component
struct TextInputExample {
  @State inputText: string = ''

  build() {
    Column() {
      TextInput({ text: this.inputText, placeholder: '请输入手机号' })
        .type(InputType.Number)
        .enterKeyType(EnterKeyType.Search)
        .onChange((value: string) => {
          this.inputText = value
          console.log('输入的内容:', value)
        })
        .onSubmit(() => {
          console.log('提交内容:', this.inputText)
        })
        .height(40)
        .width('100%')
        .margin(10)

      Text('当前输入: ' + this.inputText)
        .fontSize(16)
        .margin(10)
    }
    .width('100%')
    .padding(20)
  }
}

2. TextArea多行输入

@Entry
@Component
struct TextAreaExample {
  @State textContent: string = ''

  build() {
    Column() {
      TextArea({ text: this.textContent, placeholder: '请输入您的反馈意见...' })
        .fontSize(16)
        .height(200)
        .width('100%')
        .onChange((value: string) => {
          this.textContent = value
        })
        .margin(10)

      Text(`已输入 ${this.textContent.length} 个字符`)
        .fontSize(14)
        .fontColor(Color.Gray)
        .margin(10)
    }
    .width('100%')
    .padding(20)
  }
}

四、富文本编辑:RichEditor组件

RichEditor提供了完整的富文本编辑能力。

@Entry
@Component
struct RichEditorExample {
  private controller: RichEditorController = new RichEditorController()

  build() {
    Column() {
      // 工具栏
      Row() {
        Button('粗体')
          .onClick(() => {
            this.controller.setBold()
          })
        Button('斜体')
          .onClick(() => {
            this.controller.setItalic()
          })
        Button('插入图片')
          .onClick(() => {
            this.controller.insertImage($r('app.media.example_image'))
          })
      }
      .margin(10)

      // 富文本编辑器
      RichEditor({ controller: this.controller })
        .height(300)
        .width('100%')
        .backgroundColor(Color.White)
        .margin(10)
    }
    .width('100%')
    .padding(20)
  }
}

五、图标集成:SymbolGlyph与SymbolSpan

1. SymbolGlyph独立图标

@Entry
@Component
struct SymbolExample {
  build() {
    Column() {
      // 独立图标显示
      SymbolGlyph($r('sys.ic_public_favorite_filled'))
        .symbolSize(40)
        .symbolColor(Color.Red)
        .margin(10)

      // 多个图标排列
      Row() {
        SymbolGlyph($r('sys.ic_public_home'))
        SymbolGlyph($r('sys.ic_public_search'))
        SymbolGlyph($r('sys.ic_public_settings'))
      }
      .justifyContent(FlexAlign.SpaceAround)
      .width('100%')
      .margin(10)
    }
    .width('100%')
    .padding(20)
  }
}

2. SymbolSpan文本内图标

@Entry
@Component
struct SymbolSpanExample {
  build() {
    Column() {
      Text() {
        Span('收藏 ')
        SymbolSpan($r('sys.ic_public_favorite_filled'), {
          symbolSize: 20,
          symbolColor: Color.Red
        })
        Span(' 这条内容')
      }
      .fontSize(18)
      .margin(10)

      Text() {
        Span('联系人: ')
        SymbolSpan($r('sys.ic_public_person'))
        Span(' 张三 · ')
        SymbolSpan($r('sys.ic_public_phone'))
        Span(' 13800138000')
      }
      .fontSize(16)
      .margin(10)
    }
    .width('100%')
    .padding(20)
  }
}

六、属性字符串:StyledString编程式文本构建

@Entry
@Component
struct StyledStringExample {
  private styledContent: StyledString = this.createStyledText()

  // 创建样式化文本
  createStyledText(): StyledString {
    let mutableString = new MutableStyledString()
    
    // 添加标题
    mutableString.addText('通知公告\n', {
      fontSize: 20,
      fontWeight: FontWeight.Bold,
      fontColor: Color.Black
    })

    // 添加内容
    mutableString.addText('尊敬的用户:\n', {
      fontSize: 16,
      fontColor: Color.Blue
    })

    mutableString.addText('系统将于今晚20:00-22:00进行维护升级,期间可能无法正常使用服务。给您带来的不便,敬请谅解!', {
      fontSize: 14,
      fontColor: Color.Gray
    })

    // 添加重要提示
    mutableString.addText('\n\n重要提示:', {
      fontSize: 16,
      fontWeight: FontWeight.Bold,
      fontColor: Color.Red
    })

    mutableString.addText('请提前保存您的工作内容。', {
      fontSize: 14,
      fontColor: Color.Red
    })

    return mutableString.getString()
  }

  build() {
    Column() {
      Text(this.styledContent)
        .textAlign(TextAlign.Start)
        .margin(10)
    }
    .width('100%')
    .padding(20)
  }
}

七、高级图文混排实战

@Entry
@Component
struct AdvancedTextLayoutExample {
  build() {
    Column() {
      // 复杂图文混排
      Text() {
        Span('今日新闻')
          .fontSize(24)
          .fontWeight(FontWeight.Bold)
          .fontColor(Color.Black)
        
        Span('\n\n')
        
        Span('科技前沿: ')
          .fontSize(18)
          .fontWeight(FontWeight.Medium)
        
        SymbolSpan($r('sys.ic_public_lightbulb'))
          .symbolSize(18)
          .symbolColor(Color.Orange)
        
        Span(' 人工智能取得重大突破,研究人员开发出新型算法...')
          .fontSize(16)
        
        Span('\n\n')
        
        Span('财经快讯: ')
          .fontSize(18)
          .fontWeight(FontWeight.Medium)
          .fontColor(Color.Green)
        
        SymbolSpan($r('sys.ic_public_trending_up'))
          .symbolSize(18)
          .symbolColor(Color.Green)
        
        Span(' 股市今日大涨,科技板块领涨...')
          .fontSize(16)
      }
      .textAlign(TextAlign.Start)
      .margin(10)

      // 分隔线
      Divider()
        .margin(10)

      // 带背景的文本块
      Text('特别提醒:本次更新包含重要安全补丁,建议尽快安装。')
        .fontSize(14)
        .fontColor(Color.White)
        .backgroundColor(Color.Red)
        .padding(10)
        .borderRadius(8)
        .width('100%')
        .textAlign(TextAlign.Center)
        .margin(10)
    }
    .width('100%')
    .padding(20)
  }
}

八、综合应用:完整的文本处理示例

@Entry
@Component
struct ComprehensiveTextExample {
  @State username: string = ''
  @State comment: string = ''
  private editorController: RichEditorController = new RichEditorController()

  build() {
    Column() {
      // 用户信息输入区
      Text('用户评论')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 20, bottom: 10 })

      TextInput({ placeholder: '请输入您的姓名', text: this.username })
        .onChange((value: string) => {
          this.username = value
        })
        .margin(10)
        .width('100%')
        .height(40)

      // 富文本编辑器
      Text('评论内容:')
        .fontSize(16)
        .fontWeight(FontWeight.Medium)
        .margin({ top: 20, bottom: 5 })
        .align(Alignment.Start)

      RichEditor({ controller: this.editorController })
        .height(200)
        .width('100%')
        .backgroundColor(Color.White)
        .border({ width: 1, color: Color.Gray })
        .margin(10)

      // 操作按钮
      Row() {
        Button('提交评论')
          .onClick(() => {
            this.submitComment()
          })
          .backgroundColor(Color.Blue)
          .fontColor(Color.White)

        Button('清空内容')
          .onClick(() => {
            this.clearContent()
          })
          .margin({ left: 10 })
      }
      .margin(20)
      .width('100%')
      .justifyContent(FlexAlign.Center)
    }
    .width('100%')
    .padding(20)
  }

  private submitComment(): void {
    console.log('用户评论提交:', this.username)
    // 这里可以添加提交逻辑
  }

  private clearContent(): void {
    this.username = ''
    this.editorController.clear()
  }
}

总结

ArkTS的文本组件体系提供了从简单到复杂的全方位文本处理能力。通过Text和Span实现基础文本展示,TextInput和TextArea处理用户输入,RichEditor提供完整的富文本编辑功能,Symbol系列组件优雅地集成图标,StyledString实现编程式文本构建,最终通过图文混排技术创建出丰富的界面效果。

这些组件不仅功能强大,而且性能优异,能够满足各种场景下的文本处理需求。开发者可以根据具体需求选择合适的组件,或者组合使用多个组件来实现复杂的文本交互效果。

在实际开发中,建议:

  1. 根据场景选择合适的文本组件
  2. 合理使用样式属性保持UI一致性
  3. 注意性能优化,特别是大量文本渲染时
  4. 充分利用Symbol图标提升用户体验
  5. 复杂文本考虑使用StyledString动态构建

掌握这些文本组件的使用,将帮助你打造出更加精美、交互丰富的鸿蒙应用。