鸿蒙5.0版开发:ArkTS基础组件(Text)

99 篇文章 0 订阅
95 篇文章 0 订阅

Text

显示一段文本的组件。

说明:

该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。

子组件

可以包含SpanImageSpanSymbolSpanContainerSpan子组件。

接口

Text(content?: string | Resource , value?: TextOptions)

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名参数类型必填参数描述
contentstring | Resource文本内容。包含子组件Span且未设置属性字符串时不生效,显示Span内容,并且此时text组件的样式不生效。
默认值:’ ’
value11+TextOptions文本组件初始化选项。

属性

除支持通用属性文本通用属性外,还支持以下属性:

textAlign

textAlign(value: TextAlign)

设置文本段落在水平方向的对齐方式。

文本段落宽度占满Text组件宽度。

可通过align属性控制文本段落在垂直方向上的位置,此组件中不可通过align属性控制文本段落在水平方向上的位置,即align属性中Alignment.TopStart、Alignment.Top、Alignment.TopEnd效果相同,控制内容在顶部,Alignment.Start、Alignment.Center、Alignment.End效果相同,控制内容垂直居中,Alignment.BottomStart、Alignment.Bottom、Alignment.BottomEnd效果相同,控制内容在底部。结合TextAlign属性可控制内容在水平方向的位置。

当textAlign属性设置为TextAlign.JUSTIFY时,需要根据文本内容设置wordBreak属性,且最后一行文本不参与两端对齐,为水平对齐首部效果。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueTextAlign文本段落在水平方向的对齐方式。
默认值:TextAlign.Start

textOverflow

textOverflow(value: { overflow: TextOverflow })

设置文本超长时的显示方式。

文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。从API version 11开始,建议优先组合wordBreak属性设置为WordBreak.BREAK_ALL方式实现字母为单位进行截断,使用示例

当overflow设置为TextOverflow.None、TextOverflow.Clip、TextOverflow.Ellipsis时,需配合maxLines使用,单独设置不生效。设置TextOverflow.None与TextOverflow.Clip效果一样。

当overflow设置为TextOverflow.MARQUEE时,文本在一行内滚动显示,设置maxLines及copyOption属性均不生效。在文本不可滚动时,设置textAlign属性生效;在文本可滚动时,设置textAlign属性不生效。在跑马灯模式下,Text组件clip属性默认为true。

从API version 12开始,当overflow设置为TextOverflow.MARQUEE时,支持ImageSpan组件,文本和图片在一行内滚动显示。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
value{overflow: TextOverflow}文本超长时的显示方式。
默认值:{overflow: TextOverflow.Clip}

maxLines

maxLines(value: number)

设置文本的最大行数。默认情况下,文本是自动折行的,如果指定此属性,则文本最多不会超过指定的行。如果有多余的文本,可以通过textOverflow来指定截断方式。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valuenumber文本的最大行数。

lineHeight

lineHeight(value: number | string | Resource)

设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,number类型时单位为fp。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valuenumber | string | Resource文本的文本行高。

decoration

decoration(value: DecorationStyleInterface)

设置文本装饰线样式及其颜色。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueDecorationStyleInterface12+文本装饰线样式对象。
默认值:
{
 type: TextDecorationType.None,
 color: Color.Black,
 style: TextDecorationStyle.SOLID 
}
说明:
style参数不支持卡片能力。

baselineOffset

baselineOffset(value: number | string)

设置文本基线的偏移量,设置该值为百分比时,按默认值显示。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valuenumber | string文本基线的偏移量。
默认值:0

letterSpacing

letterSpacing(value: number | string)

设置文本字符间距。设置该值为百分比时,按默认值显示。设置该值为0时,按默认值显示。

当取值为负值时,文字会发生压缩,负值过小时会将组件内容区大小压缩为0,导致无内容显示。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valuenumber | string文本字符间距。

minFontSize

minFontSize(value: number | string | Resource)

设置文本最小显示字号。

需配合maxFontSize以及maxlines或布局大小限制使用,单独设置不生效,对子组件和属性字符串不生效。

自适应字号生效时,fontSize设置不生效。

minFontSize小于或等于0时,自适应字号不生效。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valuenumber | string | Resource文本最小显示字号。

maxFontSize

maxFontSize(value: number | string | Resource)

设置文本最大显示字号。

需配合minFontSize以及maxlines或布局大小限制使用,单独设置不生效,对子组件和属性字符串不生效。

自适应字号生效时,fontSize设置不生效。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valuenumber | string | Resource文本最大显示字号。

textCase

textCase(value: TextCase)

设置文本大小写。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueTextCase文本大小写。
默认值:TextCase.Normal

copyOption9+

copyOption(value: CopyOptions)

设置组件是否支持文本可复制粘贴。设置copyOptions为CopyOptions.InApp或者CopyOptions.LocalDevice,长按文本,会弹出文本选择菜单,可选中文本并进行复制、全选操作。

由于卡片没有长按事件,此场景下长按文本,不会弹出文本选择菜单。

卡片能力: 从API version 9开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueCopyOptions组件是否支持文本可复制粘贴。
默认值:CopyOptions.None

draggable9+

draggable(value: boolean)

设置选中文本拖拽效果。

不能和onDragStart事件同时使用。

需配合CopyOptions一起使用,设置copyOptions为CopyOptions.InApp或者CopyOptions.LocalDevice,并且draggable设置为true时,支持对选中文本的拖拽以及选中内容复制到输入框。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueboolean选中文本拖拽效果。
默认值:false

font10+

font(value: Font)

设置文本样式。包括字体大小、字体粗细、字体族和字体风格。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueFont文本样式。

textShadow10+

textShadow(value: ShadowOptions | Array<ShadowOptions>)

设置文字阴影效果。

不支持fill字段,不支持智能取色模式。

从API version 11开始,该接口支持以数组形式入参,实现多重文字阴影。

卡片能力: 从API version 10开始,该接口支持在ArkTS卡片中使用。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueShadowOptions |  Array<ShadowOptions>11+文字阴影效果。

heightAdaptivePolicy10+

heightAdaptivePolicy(value: TextHeightAdaptivePolicy)

设置文本自适应高度的方式。

当设置为TextHeightAdaptivePolicy.MAX_LINES_FIRST时,优先使用maxlines属性来调整文本高度。如果使用maxLines属性的布局大小超过了布局约束,则尝试在minFontSizemaxFontSize的范围内缩小字体以显示更多文本。

当设置为TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST时,优先使用minFontSize属性来调整文本高度。如果使用minFontSize属性可以将文本布局在一行中,则尝试在minFontSize和maxFontSize的范围内增大字体并使用最大可能的字体大小。

当设置为TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST时,优先使用布局约束来调整文本高度。如果布局大小超过布局约束,则尝试在minFontSize和maxFontSize的范围内缩小字体以满足布局约束。如果将字体大小缩小到minFontSize后,布局大小仍然超过布局约束,则删除超过布局约束的行。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueTextHeightAdaptivePolicy文本自适应高度的方式。
默认值:TextHeightAdaptivePolicy.MAX_LINES_FIRST

textIndent10+

textIndent(value: Length)

设置首行文本缩进。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueLength首行文本缩进。
默认值:0

wordBreak11+

wordBreak(value: WordBreak)

设置断行规则。WordBreak.BREAK_ALL与{overflow: TextOverflow.Ellipsis},maxLines组合使用可实现英文单词按字母截断,超出部分以省略号显示

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueWordBreak断行规则。
默认值:WordBreak.BREAK_WORD

selection11+

selection(selectionStart: number, selectionEnd: number)

设置选中区域。选中区域高亮且显示手柄和文本选择菜单。

当copyOption设置为CopyOptions.None时,设置selection属性不生效。

当overflow设置为TextOverflow.MARQUEE时,设置selection属性不生效。

当selectionStart大于等于selectionEnd时不选中。可选范围为[0, textSize],textSize为文本内容最大字符数,入参小于0处理为0,大于textSize处理为textSize。

当selectionStart或selectionEnd在截断不可见区域时不选中。截断为false时超出父组件的文本选中区域生效。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
selectionStartnumber所选文本的起始位置。
默认值:-1
selectionEndnumber所选文本的结束位置。
默认值:-1

ellipsisMode11+

ellipsisMode(value: EllipsisMode)

设置省略位置。ellipsisMode属性需要配合overflow设置为TextOverflow.Ellipsis以及maxLines使用,单独设置ellipsisMode属性不生效。

EllipsisMode.START和EllipsisMode.CENTER仅在单行超长文本生效。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueEllipsisMode省略位置。
默认值:EllipsisMode.END

enableDataDetector11+

enableDataDetector(enable: boolean)

设置使能文本识别。所识别实体的fontColor和decoration会被更改为如下样式:

fontColor:Color.Blue
decoration: {
type: TextDecorationType.Underline,
color: Color.Blue,
style: TextDecorationStyle.SOLID
}

该接口依赖设备底层应具有文本识别能力,否则设置不会生效。

当enableDataDetector设置为true,同时不设置dataDetectorConfig属性时,默认识别所有类型的实体。

当copyOption设置为CopyOptions.None时,该功能不会生效。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
enableboolean使能文本识别。
默认值: false

dataDetectorConfig11+

dataDetectorConfig(config: TextDataDetectorConfig)

设置文本识别配置。

需配合enableDataDetector一起使用,设置enableDataDetector为true时,dataDetectorConfig的配置才能生效。

当有两个实体A、B重叠时,按以下规则保留实体:

1. 若A ⊂ B,则保留B,反之则保留A。

2. 当A ⊄ B且B ⊄ A时,若A.start < B.start,则保留A,反之则保留B。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
configTextDataDetectorConfig文本识别配置。
默认值:{
types: [ ],
onDetectResultUpdate: null
}

bindSelectionMenu11+

bindSelectionMenu(spanType: TextSpanType, content: CustomBuilder, responseType: TextResponseType, options?: SelectionMenuOptions)

设置自定义选择菜单。

bindSelectionMenu长按响应时长为600ms,bindContextMenu长按响应时长为800ms,同时绑定且触发方式均为长按时,优先响应bindSelectionMenu。

自定义菜单超长时,建议内部嵌套Scroll组件使用,避免键盘被遮挡。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
spantypeTextSpanType选择菜单的类型。
默认值:TextSpanType.TEXT
contentCustomBuilder选择菜单的内容。
responseTypeTextResponseType选择菜单的响应类型。
默认值:TextResponseType.LONG_PRESS
optionsSelectionMenuOptions选择菜单的选项。

fontFeature12+

fontFeature(value: string)

设置文字特性效果,比如数字等宽的特性。

格式为:normal | <feature-tag-value>

<feature-tag-value>的格式为:<string> [ <integer> | on | off ]

<feature-tag-value>的个数可以有多个,中间用’,'隔开。

例如,使用等宽数字的输入格式为:“ss01” on。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valuestring文字特性效果。

设置 Font Feature 属性,Font Feature 是 OpenType 字体的高级排版能力,如支持连字、数字等宽等特性,一般用在自定义字体中,其能力需要字体本身支持。 更多 Font Feature 能力介绍可参考 https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop 和 https://sparanoid.com/lab/opentype-features/

说明:

不支持Text内同时存在文本内容和Span或ImageSpan子组件。如果同时存在,只显示Span或ImageSpan内的内容。

字体排版引擎会对开发者传入的宽度width进行向下取整,保证是整型像素后进行排版。如果字体排版引擎向上取整,可能会出现文字右侧被截断。

当多个Text组件在Row容器内布局且没有设置具体的布局分配信息时,Text会以Row的最大尺寸进行布局。如果需要子组件主轴累加的尺寸不超过Row容器主轴的尺寸,可以设置layoutWeight或者是以Flex布局来约束子组件的主轴尺寸。

lineSpacing12+

lineSpacing(value: LengthMetrics)

设置文本的行间距,设置值不大于0时,取默认值0。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valueLengthMetrics文本的行间距。默认值:0

privacySensitive12+

privacySensitive(supported: boolean)

设置是否支持卡片敏感隐私信息。

卡片能力: 从API version 12开始,该接口支持在ArkTS卡片中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
supportedboolean是否支持卡片敏感隐私信息。
默认值为false,当设置为true时,隐私模式下文字将被遮罩为横杠“-”样式。
说明:
设置null则不敏感。

lineBreakStrategy12+

lineBreakStrategy(strategy: LineBreakStrategy)

设置折行规则。该属性在wordBreak不等于breakAll的时候生效,不支持连词符。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
strategyLineBreakStrategy文本的折行规则。
默认值:LineBreakStrategy.GREEDY

TextDataDetectorConfig11+对象说明

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数名类型必填说明
typesTextDataDetectorType[]设置文本识别的实体类型。设置types为null或者[]时,识别所有类型的实体,否则只识别指定类型的实体。
onDetectResultUpdate(result: string) => void文本识别成功后,触发onDetectResultUpdate回调。
- result:文本识别的结果,Json格式。

事件

除支持通用事件外,还支持以下事件:

onCopy11+

onCopy(callback:(value: string) => void)

长按文本内部区域弹出剪贴板后,点击剪切板复制按钮,触发该回调。目前文本复制仅支持文本。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
valuestring复制的文本内容。

onTextSelectionChange11+

onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)

文本选择的位置发生变化时,触发该回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
selectionStartnumber所选文本的起始位置。
selectionEndnumber所选文本的结束位置。

TextOptions11+

Text初始化参数。

名称类型必填说明
controllerTextController文本控制器。

TextController11+

Text组件的控制器。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

导入对象

controller: TextController = new TextController()

closeSelectionMenu

closeSelectionMenu(): void

关闭自定义选择菜单或系统默认选择菜单。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

setStyledString12+

setStyledString(value: StyledString): void

触发绑定或更新属性字符串。

参数:

参数名参数类型必填参数描述
valueStyledString属性字符串。
说明:
StyledString的子类MutableStyledString也可以作为入参值。

示例

示例1

textAlign、maxLines、textOverflow、lineHeight属性接口使用示例

// xxx.ets
@Extend(Text)
function style(TextAlign: TextAlign) {
  .textAlign(TextAlign)
  .fontSize(12)
  .border({ width: 1 })
  .padding(10)
  .width('100%')
}

@Entry
@Component
struct TextExample1 {
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
      // 文本水平方向对齐方式设置
      // 单行文本
      Text('textAlign').fontSize(9).fontColor(0xCCCCCC)
      Text('TextAlign set to Center.')
        .style(TextAlign.Center)
      Text('TextAlign set to Start.')
        .style(TextAlign.Start)
      Text('TextAlign set to End.')
        .style(TextAlign.End)

      // 多行文本
      Text('This is the text content with textAlign set to Center.')
        .style(TextAlign.Center)
      Text('This is the text content with textAlign set to Start.')
        .style(TextAlign.Start)
      Text('This is the text content with textAlign set to End.')
        .style(TextAlign.End)


      // 文本超长时显示方式
      Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC)
      // 超出maxLines截断内容展示
      Text('This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content. This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content.')
        .textOverflow({ overflow: TextOverflow.Clip })
        .maxLines(1)
        .style(TextAlign.Start)

      // 超出maxLines展示省略号
      Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.')
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .maxLines(1)
        .style(TextAlign.Start)

      Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text with the line height set. This is the text with the line height set.')
        .style(TextAlign.Start)
      Text('This is the text with the line height set. This is the text with the line height set.')
        .style(TextAlign.Start)
        .lineHeight(20)
    }.height(600).width(340).padding({ left: 35, right: 35, top: 35 })
  }
}

示例2

decoration、baselineOffset、letterSpacing、textCase属性接口使用示例

@Extend(Text)
function style() {
  .fontSize(12)
  .border({ width: 1 })
  .padding(10)
  .width('100%')
}

@Entry
@Component
struct TextExample2 {
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
      Text('decoration').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text content with the decoration set to LineThrough and the color set to Red.')
        .decoration({
          type: TextDecorationType.LineThrough,
          color: Color.Red
        })
        .style()

      Text('This is the text content with the decoration set to Overline and the color set to Red.')
        .decoration({
          type: TextDecorationType.Overline,
          color: Color.Red,
          style: TextDecorationStyle.DOTTED
        })
        .style()

      Text('This is the text content with the decoration set to Underline and the color set to Red.')
        .decoration({
          type: TextDecorationType.Underline,
          color: Color.Red,
          style: TextDecorationStyle.WAVY
        })
        .style()

      // 文本基线偏移
      Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text content with baselineOffset 0.')
        .baselineOffset(0)
        .style()
      Text('This is the text content with baselineOffset 30.')
        .baselineOffset(30)
        .style()
      Text('This is the text content with baselineOffset -20.')
        .baselineOffset(-20)
        .style()

      // 文本字符间距
      Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text content with letterSpacing 0.')
        .letterSpacing(0)
        .style()
      Text('This is the text content with letterSpacing 3.')
        .letterSpacing(3)
        .style()
      Text('This is the text content with letterSpacing -1.')
        .letterSpacing(-1)
        .style()

      Text('textCase').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text content with textCase set to Normal.')
        .textCase(TextCase.Normal)
        .style()
      // 文本全小写展示
      Text('This is the text content with textCase set to LowerCase.')
        .textCase(TextCase.LowerCase)
        .style()
      // 文本全大写展示
      Text('This is the text content with textCase set to UpperCase.')
        .textCase(TextCase.UpperCase)
        .style()

    }.height(700).width(350).padding({ left: 35, right: 35, top: 35 })
  }
}

示例3

textShadow,heightAdaptivePolicy,TextOverflow.MARQUEE使用示例:

@Extend(Text)
function style(HeightAdaptivePolicy: TextHeightAdaptivePolicy) {
  .width('80%')
  .height(90)
  .borderWidth(1)
  .minFontSize(10)
  .maxFontSize(30)
  .maxLines(2)
  .textOverflow({ overflow: TextOverflow.Ellipsis })
  .heightAdaptivePolicy(HeightAdaptivePolicy)
}

@Entry
@Component
struct TextExample3 {
  build() {
    Column({ space: 8 }) {
      Text('textShadow').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
      // 设置文字阴影效果
      Text('textShadow')
        .width('80%')
        .height(55)
        .fontSize(40)
        .lineHeight(55)
        .textAlign(TextAlign.Center)
        .textShadow({
          radius: 10,
          color: Color.Black,
          offsetX: 0,
          offsetY: 0
        })
        .borderWidth(1)
      Divider()
      // 设置文本自适应高度的方式
      Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
      Text('This is the text with the height adaptive policy set')
        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
      Text('This is the text with the height adaptive policy set')
        .style(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
      Text('This is the text with the height adaptive policy set')
        .style(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
      Divider()
      Text('marquee').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
      // 设置文本超长时以跑马灯的方式展示
      Text('This is the text with the text overflow set marquee')
        .width(300)
        .borderWidth(1)
        .textOverflow({ overflow: TextOverflow.MARQUEE })
    }
  }
}

示例4

ellipsisMode和wordBreak使用示例

// xxx.ets
@Entry
@Component
struct TextExample4 {
  @State text: string =
    'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.'
  @State ellipsisModeIndex: number = 0;
  @State ellipsisMode: EllipsisMode[] = [EllipsisMode.START, EllipsisMode.CENTER, EllipsisMode.END]
  @State ellipsisModeStr: string[] = ['START', 'CENTER', 'END']
  @State wordBreakIndex: number = 0;
  @State wordBreak: WordBreak[] = [WordBreak.NORMAL, WordBreak.BREAK_ALL, WordBreak.BREAK_WORD]
  @State wordBreakStr: string[] = ['NORMAL', 'BREAK_ALL', 'BREAK_WORD']
  @State textClip: boolean = false

  build() {
    Column({ space: 10 }) {
      Text(this.text)
        .fontSize(16)
        .border({ width: 1 })
        .lineHeight(20)
        .maxLines(1)
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .ellipsisMode(this.ellipsisMode[this.ellipsisModeIndex])
        .width(300)
        .margin({ left: 20, top: 20 })

      Row() {
        Button('更改省略号位置:' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick(() => {
          this.ellipsisModeIndex++
          if (this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) {
            this.ellipsisModeIndex = 0
          }
        })
      }

      Text('This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.')
        .fontSize(12)
        .border({ width: 1 })
        .wordBreak(WordBreak.NORMAL)
        .lineHeight(20)
        .maxLines(2)
        .clip(this.textClip)
        .width(260)
      Row() {
        Button('切换clip:' + this.textClip).onClick(() => {
          this.textClip = !this.textClip
        })
      }

      Text(this.text)
        .fontSize(12)
        .border({ width: 1 })
        .maxLines(2)
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .wordBreak(this.wordBreak[this.wordBreakIndex])
        .lineHeight(20)
        .width(260)
      Row() {
        Button('更改wordBreak模式:' + this.wordBreakStr[this.wordBreakIndex]).onClick(() => {
          this.wordBreakIndex++
          if (this.wordBreakIndex > (this.wordBreakStr.length - 1)) {
            this.wordBreakIndex = 0
          }
        })
      }
    }
  }
}

示例5

selection和onCopy使用示例

@Entry
@Component
struct TextExample5 {
  @State onCopy: string = ''
  @State text: string = 'This is set selection to Selection text content This is set selection to Selection text content.'
  @State start: number = 0
  @State end: number = 20

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
      Text(this.text)
        .fontSize(12)
        .border({ width: 1 })
        .lineHeight(20)
        .margin(30)
        .copyOption(CopyOptions.InApp)
        .selection(this.start, this.end)
        .onCopy((value: string) => {
          this.onCopy = value
        })
      Button('Set text selection')
        .margin({left:20})
        .onClick(() => {
          // 变更文本选中起始点、终点
          this.start = 10
          this.end = 30
        })
      Text(this.onCopy).fontSize(12).margin(10).key('copy')
    }.height(600).width(335).padding({ left: 35, right: 35, top: 35 })
  }
}

示例6

enableDataDetector和dataDetectorConfig使用示例

@Entry
@Component
struct TextExample6 {
  @State phoneNumber: string = '(86) (755) ********';
  @State url: string = 'www.********.com';
  @State email: string = '***@example.com';
  @State address: string = 'XX省XX市XX区XXXX';
  @State datetime: string = 'XX年XX月XX日XXXX';
  @State enableDataDetector: boolean = true;
  @State types: TextDataDetectorType[] = [];

  build() {
    Row() {
      Column() {
        Text(
          '电话号码:' + this.phoneNumber + '\n' +
          '链接:' + this.url + '\n' +
          '邮箱:' + this.email + '\n' +
          '地址:' + this.address + '\n' +
          '时间:' + this.datetime
        )
          .fontSize(16)
          .copyOption(CopyOptions.InApp)
          .enableDataDetector(this.enableDataDetector)
          .dataDetectorConfig({types : this.types, onDetectResultUpdate: (result: string)=>{}})
          .textAlign(TextAlign.Center)
          .borderWidth(1)
          .padding(10)
          .width('100%')
      }
      .width('100%')
    }
    .height('100%')
  }
}

示例7

bindSelectionMenu,onTextSelectionChange及closeSelectionMenu使用示例

@Entry
@Component
struct TextExample7 {
  controller: TextController = new TextController();
  options: TextOptions = { controller: this.controller };

  build() {
    Column() {
      Column() {
        Text(undefined, this.options) {
          Span('Hello World')
          ImageSpan($r('app.media.icon'))
            .width('100px')
            .height('100px')
            .objectFit(ImageFit.Fill)
            .verticalAlign(ImageSpanAlignment.CENTER)
        }
        .copyOption(CopyOptions.InApp)
        .bindSelectionMenu(TextSpanType.IMAGE, this.LongPressImageCustomMenu, TextResponseType.LONG_PRESS, {
          onDisappear: () => {
            console.info(`自定义选择菜单关闭时回调`);
          },
          onAppear: () => {
            console.info(`自定义选择菜单弹出时回调`);
          }
        })
        .bindSelectionMenu(TextSpanType.TEXT, this.RightClickTextCustomMenu, TextResponseType.RIGHT_CLICK)
        .bindSelectionMenu(TextSpanType.MIXED, this.SelectMixCustomMenu, TextResponseType.SELECT)
        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
          console.info(`文本选中区域变化回调, selectionStart: ${selectionStart}, selectionEnd: ${selectionEnd}`);
        })
        .borderWidth(1)
        .borderColor(Color.Red)
        .width(200)
        .height(100)
      }
      .width('100%')
      .backgroundColor(Color.White)
      .alignItems(HorizontalAlign.Start)
      .padding(25)
    }
    .height('100%')
  }

  @Builder
  RightClickTextCustomMenu() {
    Column() {
      Menu() {
        MenuItemGroup() {
          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 1", labelInfo: "" })
            .onClick((event) => {
              this.controller.closeSelectionMenu();
            })
          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 2", labelInfo: "" })
          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 3", labelInfo: "" })
        }
      }
      .MenuStyles()
    }
  }

  @Builder
  LongPressImageCustomMenu() {
    Column() {
      Menu() {
        MenuItemGroup() {
          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 1", labelInfo: "" })
            .onClick((event) => {
              this.controller.closeSelectionMenu();
            })
          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 2", labelInfo: "" })
          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 3", labelInfo: "" })
        }
      }
      .MenuStyles()
    }
  }

  @Builder
  SelectMixCustomMenu() {
    Column() {
      Menu() {
        MenuItemGroup() {
          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 1", labelInfo: "" })
            .onClick((event) => {
              this.controller.closeSelectionMenu();
            })
          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 2", labelInfo: "" })
          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 3", labelInfo: "" })
        }
      }
      .MenuStyles()
    }
  }
}

@Extend(Menu)
function MenuStyles() {
  .radius($r('sys.float.ohos_id_corner_radius_card'))
  .clip(true)
  .backgroundColor('#F0F0F0')
}

示例8

fontFeature、lineSpacing和lineBreakStrategy使用示例。

import { LengthMetrics } from '@ohos.arkui.node'
@Extend(Text) function lineSpacingValue(LineSpacing: LengthMetrics|undefined) {
  .lineSpacing(LineSpacing)
  .fontSize(12)
  .border({ width: 1 })
}
@Entry
@Component
struct TextExample8 {
  @State message1: string = "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" +
    "The built-in components include buttons radio buttonsprogress indicators and text You can set the rendering effectof thesecomponents in method chaining mode," +
    "page components are divided into independent UI units to implementindependent creation development and reuse of different units on pages making pages more engineering-oriented.";
  @State lineBreakStrategyIndex: number = 0;
  @State lineBreakStrategy: LineBreakStrategy[] = [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED]
  @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED']
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
      Text('lineSpacing').fontSize(9).fontColor(0xCCCCCC)
      Text('This is a context with no lineSpacing set.')
        .lineSpacingValue(undefined)
      Text( 'This is a context with lineSpacing set to 20_px.')
        .lineSpacingValue(LengthMetrics.px(20))
      Text('This is the context with lineSpacing set to 20_vp.')
        .lineSpacingValue(LengthMetrics.vp(20))
      Text('This is the context with lineSpacing set to 20_fp.')
        .lineSpacingValue(LengthMetrics.fp(20))
      Text('This is the context with lineSpacing set to 20_lpx.')
        .lineSpacingValue(LengthMetrics.lpx(20))
      Text('This is the context with lineSpacing set to 100%.')
        .lineSpacingValue(LengthMetrics.percent(1))
      Text('fontFeature').fontSize(9).fontColor(0xCCCCCC)
      Text('This is ss01 on : 0123456789')
        .fontSize(20)
        .fontFeature("\"ss01\" on")
      Text('This is ss01 off: 0123456789')
        .fontSize(20)
        .fontFeature("\"ss01\" off")
      Text('lineBreakStrategy').fontSize(9).fontColor(0xCCCCCC)
      Text(this.message1)
        .fontSize(12)
        .border({ width: 1 })
        .padding(10)
        .width('100%')
        .lineBreakStrategy(this.lineBreakStrategy[this.lineBreakStrategyIndex])
      Row() {
        Button('更改lineBreakStrategy模式:' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => {
          this.lineBreakStrategyIndex++
          if(this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) {
            this.lineBreakStrategyIndex = 0
          }
        })
      }
    }.height(600).width(350).padding({ left: 35, right: 35, top: 35 })
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值