目录

Text Display (Text/Span)

The Text component is used to display textual content. It can be bound to a custom text selection menu, allowing users to select features as needed. Additionally, you can extend this custom menu to add more options, further enhancing user experience. The Span component is used to display inline text.

For details, see the API documentation for Text and Span.

For details, see FAQs About Text Display (Text/Span).

Creating Text

You can create text in either of the following ways:

Adding Child Components

The Span component can only act as a child of the Text and RichEditor components. You can add one or more Span child components to a Text component to display a piece of information, such as the product description and statement of commitment.

Creating a Custom Text Style

The Text component supports custom text style configuration. The following table lists the key attributes for text styling.

Name Description
baselineOffset Offset of the text baseline.
contentTransition Digital flip animation effect.
copyOption Whether text can be copied and pasted.
decoration Text decoration, such as the line style, color, and thickness.
enableAutoSpacing Whether to enable automatic spacing between Chinese and Western characters.
enableDataDetector Whether to enable recognition for special entities within the text.
font Font-related attributes.
fontColor Text color.
fontFamily Font family.
fontFeature Typographic features, such as numeric width adjustment.
fontSize Font size.
fontStyle Font style.
fontWeight Font weight.
halfLeading Whether half leading is enabled.
heightAdaptivePolicy Font size adjustment strategy for adaptive text layout.
letterSpacing Letter spacing.
lineHeight Line height.
lineSpacing Spacing between lines.
marqueeOptions Marquee behavior, including the enabled status, step, loop count, and direction.
maxFontSize Maximum font size for adaptive scaling.
maxLines Maximum number of visible lines.
minFontSize Minimum font size for adaptive scaling.
optimizeTrailingSpace Whether to optimize trailing spaces at line endings.
privacySensitive Whether to enable privacy mode on widgets.
shaderStyle Gradient color effect.
textCase Text case conversion.
textAlign Horizontal alignment mode of text paragraphs.
textIndent Indent of the first line of text.
textOverflow Handling of overflow text.
textSelectable Whether text can be selected.
textVerticalAlign Vertical alignment mode of text paragraphs.
wordBreak Word breaking rule.

The following examples demonstrate usage of common APIs.

Adding Events

You can bind the Text component to the onClick, onTouch, or other universal events to respond to user operations.

// xxx.ets
import { hilog } from '@kit.PerformanceAnalysisKit';
@Entry
@Component
struct GeneralEvents {
  @State textStr1: string = '';
  @State textStr2: string = '';

  build() {
    NavDestination() {
      Row() {
        Column() {
          Text('This is a text component.')
            .fontSize(30)
            .onClick(() => {
              hilog.info(0x0000, 'Sample_TextComponent', 'Text onClick is triggering');
              this.textStr1 = 'Text onClick is triggering';
            })
            .onTouch(() => {
              hilog.info(0x0000, 'Sample_TextComponent', 'Text onTouch is triggering');
              this.textStr2 = 'Text onTouch is triggering';
            })
          Text('onClick: ' + this.textStr1)
            .fontSize(20)
          Text('onTouch: ' + this.textStr2)
            .fontSize(20)
        }.width('100%')
      }
      .height('100%')
    }
    // ···
  }
}

Setting Vertical Alignment

Since API version 20, use the textVerticalAlign attribute to vertically align text paragraphs.

Configuring the Selection Menu

[h2]Displaying the Selection Menu

[h2]Closing the Selection Menu

When using the Text component, you can close the selection state and menu by clicking blank areas in the following scenarios:

[h2]Disabling System Menu Callbacks and Custom Extended Menu Items

Since API version 12, use editMenuOptions to disable system menu callbacks and custom extended menu items .

// xxx.ets
@Entry
@Component
struct CustomAndBlockMenus {
  private static readonly CREATE_MENU_ITEM_ID_1: string = 'create1';
  private static readonly CREATE_MENU_ITEM_ID_2: string = 'create2';
  private static readonly PREPARE_MENU_ITEM_ID: string = 'prepare1';
  private controller: TextController = new TextController();
  @State private text: string = 'Text editMenuOptions';
  @State private endIndex: number = 0;
  @State blockCallbackText: string = '';

  // Auxiliary method for creating a menu item.
  private createMenuItem(id: string, content: string): TextMenuItem {
    // Replace $r('app.media.startIcon') with the image resource file you use.
    return {
      content: content,
      icon: $r('app.media.startIcon'),
      id: TextMenuItemId.of(id)
    };
  }

  // Search for the menu item index.
  private findMenuItemIndex(menuItems: Array<TextMenuItem>, menuItemId: TextMenuItemId): number {
    return menuItems.findIndex((item: TextMenuItem) => item.id.equals(menuItemId));
  }

  // Callback triggered when a menu is created.
  private onCreateMenu = (menuItems: Array<TextMenuItem>): Array<TextMenuItem> => {
    const createItem1: TextMenuItem = this.createMenuItem(
      CustomAndBlockMenus.CREATE_MENU_ITEM_ID_1,
      'create1'
    );

    const createItem2: TextMenuItem = this.createMenuItem(
      CustomAndBlockMenus.CREATE_MENU_ITEM_ID_2,
      'create2'
    );

    // Add a custom menu item.
    menuItems.push(createItem1);
    menuItems.unshift(createItem2);

    // Remove unnecessary system menu items.
    this.removeMenuItemById(menuItems, TextMenuItemId.AI_WRITER);
    this.removeMenuItemById(menuItems, TextMenuItemId.TRANSLATE);

    return menuItems;
  }

  // Remove a specified menu item.
  private removeMenuItemById(menuItems: Array<TextMenuItem>, menuItemId: TextMenuItemId): void {
    const targetIndex: number = this.findMenuItemIndex(menuItems, menuItemId);
    if (targetIndex !== -1) {
      menuItems.splice(targetIndex, 1);
    }
  }

  // Callback triggered when a menu item is clicked.
  private onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange): boolean => {
    const menuItemId: TextMenuItemId = menuItem.id;

    // Handle the custom menu item. If false is returned, the menu closes after the custom menu item is tapped.
    if (menuItemId.equals(TextMenuItemId.of(CustomAndBlockMenus.CREATE_MENU_ITEM_ID_2))) {
      let msg = 'Intercept id: create2 start:' + textRange.start + '; end:' + textRange.end;
      this.blockCallbackText = msg;
      return false;
    }
    // Handle the custom menu item. If true is returned, the menu does not close after the custom menu item is tapped.
    if (menuItemId.equals(TextMenuItemId.of(CustomAndBlockMenus.PREPARE_MENU_ITEM_ID))) {
      let msg = 'Intercept id: prepare1 start:' + textRange.start + '; end:+' + textRange.end;
      this.blockCallbackText = msg;
      return true;
    }

    // Handle the system menu item. If true is returned, the default system logic is intercepted, and the menu does not close when Copy is tapped.
    if (menuItemId.equals(TextMenuItemId.COPY)) {
      let msg = 'Intercept COPY start:' + textRange.start + '; end:' + textRange.end;
      this.blockCallbackText = msg;
      // The menu can be closed through the text controller. The handles also disappear, leaving only the selected area, which can be dismissed by tapping.
      this.controller.closeSelectionMenu();
      return true;
    }
    // Handle the system menu item. If false is returned, the default system logic is not intercepted, and the custom logic is also executed.
    if (menuItemId.equals(TextMenuItemId.SELECT_ALL)) {
      let msg = 'Allow SELECT_ALL start:' + textRange.start + '; end:' + textRange.end;
      this.blockCallbackText = msg;
      return false;
    }

    return false;
  }
  // Callback triggered when the menu is prepared.
  private onPrepareMenu = (menuItems: Array<TextMenuItem>): Array<TextMenuItem> => {
    const prepareItem: TextMenuItem = this.createMenuItem(
      CustomAndBlockMenus.PREPARE_MENU_ITEM_ID,
      `prepare1_${this.endIndex}`
    );

    menuItems.unshift(prepareItem);
    return menuItems;
  }
  // Edit menu options.
  @State private editMenuOptions: EditMenuOptions = {
    onCreateMenu: this.onCreateMenu,
    onMenuItemClick: this.onMenuItemClick,
    onPrepareMenu: this.onPrepareMenu
  };
  // Callback triggered when the text selection changes.
  private onTextSelectionChange = (selectionStart: number, selectionEnd: number): void => {
    this.endIndex = selectionEnd;
  }

  build() {
    NavDestination() {
      Column() {
        Text(this.text, { controller: this.controller })
          .fontSize(20)
          .copyOption(CopyOptions.LocalDevice)
          .editMenuOptions(this.editMenuOptions)
          .margin({ top: 100 })
          .onTextSelectionChange(this.onTextSelectionChange)
        Text(this.blockCallbackText).borderWidth(1)
      }
      .width('90%')
      .margin('5%')
    }
  }
}

[h2]Disabling System Service Menu Items

[h2]Customizing the Default Menu Refresh Behavior

Since API version 20, the onPrepareMenu callback is triggered before the menu is displayed when the text selection range changes. You can configure menu data within this callback.

// Replace $r('app.media.xxx') with the actual resource file.
// xxx.ets
import { hilog } from '@kit.PerformanceAnalysisKit';
const DOMAIN = 0x0000;
@Entry
@Component
struct PrepareMenu {
  @State text: string = 'Text editMenuOptions';
  @State endIndex: number = 0;
  onCreateMenu = (menuItems: Array<TextMenuItem>) => {
    let item1: TextMenuItem = {
      content: 'create1',
      icon: $r('app.media.startIcon'),
      id: TextMenuItemId.of('create1'),
    };
    let item2: TextMenuItem = {
      content: 'create2',
      id: TextMenuItemId.of('create2'),
      icon: $r('app.media.startIcon'),
    };
    menuItems.push(item1);
    menuItems.unshift(item2);
    return menuItems;
  }
  onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => {
    if (menuItem.id.equals(TextMenuItemId.of('create2'))) {
      hilog.info(DOMAIN, 'testTag', '%{public}s', 'intercept id: create2 start:' + textRange.start + '; end:' + textRange.end);
      return true;
    }
    if (menuItem.id.equals(TextMenuItemId.of('prepare1'))) {
      hilog.info(DOMAIN, 'testTag', '%{public}s', 'intercept id: prepare1 start:' + textRange.start + '; end:' + textRange.end);
      return true;
    }
    if (menuItem.id.equals(TextMenuItemId.COPY)) {
      hilog.info(DOMAIN, 'testTag', '%{public}s', 'intercept COPY start:' + textRange.start + '; end:' + textRange.end);
      return true;
    }
    if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
      hilog.info(DOMAIN, 'testTag', '%{public}s', 'No interception SELECT_ALL start:' + textRange.start + '; end:' + textRange.end);
      return false;
    }
    return false;
  }
  onPrepareMenu = (menuItems: Array<TextMenuItem>) => {
    let item1: TextMenuItem = {
      content: 'prepare1_' + this.endIndex,
      icon: $r('app.media.startIcon'),
      id: TextMenuItemId.of('prepare1'),
    };
    menuItems.unshift(item1);
    return menuItems;
  }
  @State editMenuOptions: EditMenuOptions = {
    onCreateMenu: this.onCreateMenu,
    onMenuItemClick: this.onMenuItemClick,
    onPrepareMenu: this.onPrepareMenu
  };

  build() {
    NavDestination() {
    Column() {
      Text(this.text)
        .fontSize(20)
        .copyOption(CopyOptions.LocalDevice)
        .editMenuOptions(this.editMenuOptions)
        .margin({ top: 100 })
        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
          this.endIndex = selectionEnd;
        })
    }
    .width('90%')
    .margin('5%')
    }
    // ...
  }
}

Configuring the AI Menu

The Text component enables AI menu display through the enableDataDetector and dataDetectorConfig attributes. The AI menu appears in the following scenarios: (1) Clicking an AI entity (recognizable content such as addresses and email addresses) displays entity recognition options. (2) After text selection, entity recognition options appear in both the text selection menu and right-click context menu.

Since API version 20, entity recognition options can be displayed in both text selection menus and right-click context menus. This feature takes effect when enableDataDetector is set to true and copyOption is set to CopyOptions.LocalDevice. The menu options include url (opening a link), email (creating an email), phoneNumber (calling), address (navigating to the location), and dateTime (creating a calendar reminder) in TextMenuItemId.

The selection range must encompass a complete AI entity for the corresponding options to appear.

Implementing Hot Search Rankings

This example demonstrates how to implement a hot search list using the maxLines, textOverflow, textAlign, and constraintSize attributes.

@Entry
@Component
struct TextHotSearch {
  build() {
    NavDestination() {
      Column({ space: 12 }) {
        // ...
          Column() {
            Row() {
              Text('1').fontSize(14).fontColor(Color.Red).margin({ left: 10, right: 10 })
              // Replace $r('app.string.TextHotSearch_textContent_one') with the actual resource file. In this example, the value in the resource file is "I am entry 1."
              Text($r('app.string.TextHotSearch_textContent_one'))
                .fontSize(12)
                .fontColor(Color.Blue)
                .maxLines(1)
                .textOverflow({ overflow: TextOverflow.Ellipsis })
                .fontWeight(300)
              // Replace $r('app.string.TextHotSearch_textContent_two') with the actual resource file. In this example, the value in the resource file is "Top Hit."
              Text($r('app.string.TextHotSearch_textContent_two'))
                .margin({ left: 6 })
                .textAlign(TextAlign.Center)
                .fontSize(10)
                .fontColor(Color.White)
                .fontWeight(600)
                .backgroundColor(0x770100)
                .borderRadius(5)
                .width(15)
                .height(14)
            }.width('100%').margin(5)

            Row() {
              Text('2').fontSize(14).fontColor(Color.Red).margin({ left: 10, right: 10 })
              /* Replace $r('app.string.TextHotSearch_textContent_three') with the actual resource file.
               * In this example, the value of this resource file is "I am hot search term 2 I am hot search term 2 I am hot search term 2 I am hot search term 2 I am hot search term 2".
               */
              Text($r('app.string.TextHotSearch_textContent_three'))
                .fontSize(12)
                .fontColor(Color.Blue)
                .fontWeight(300)
                .constraintSize({ maxWidth: 200 })
                .maxLines(1)
                .textOverflow({ overflow: TextOverflow.Ellipsis })
              // Replace $r('app.string.TextHotSearch_textContent_four') with the actual resource file. In this example, the value in the resource file is "Hot."
              Text($r('app.string.TextHotSearch_textContent_four'))
                .margin({ left: 6 })
                .textAlign(TextAlign.Center)
                .fontSize(10)
                .fontColor(Color.White)
                .fontWeight(600)
                .backgroundColor(0xCC5500)
                .borderRadius(5)
                .width(15)
                .height(14)
            }.width('100%').margin(5)

            Row() {
              Text('3').fontSize(14).fontColor(Color.Orange).margin({ left: 10, right: 10 })
              // Replace $r('app.string.TextHotSearch_textContent_five') with the actual resource file. In this example, the value in the resource file is "I am entry 3."
              Text($r('app.string.TextHotSearch_textContent_five'))
                .fontSize(12)
                .fontColor(Color.Blue)
                .fontWeight(300)
                .maxLines(1)
                .constraintSize({ maxWidth: 200 })
                .textOverflow({ overflow: TextOverflow.Ellipsis })
              // Replace $r('app.string.TextHotSearch_textContent_four') with the actual resource file. In this example, the value in the resource file is "Hot."
              Text($r('app.string.TextHotSearch_textContent_four'))
                .margin({ left: 6 })
                .textAlign(TextAlign.Center)
                .fontSize(10)
                .fontColor(Color.White)
                .fontWeight(600)
                .backgroundColor(0xCC5500)
                .borderRadius(5)
                .width(15)
                .height(14)
            }.width('100%').margin(5)

            Row() {
              Text('4').fontSize(14).fontColor(Color.Grey).margin({ left: 10, right: 10 })
              /* Replace $r('app.string.TextHotSearch_textContent_six') with the actual resource file.
               * In this example, the value of this resource file is "I am hot search term 4 I am hot search term 4 I am hot search term 4 I am hot search term 4 I am hot search term 4".
               */
              Text($r('app.string.TextHotSearch_textContent_six'))
                .fontSize(12)
                .fontColor(Color.Blue)
                .fontWeight(300)
                .constraintSize({ maxWidth: 200 })
                .maxLines(1)
                .textOverflow({ overflow: TextOverflow.Ellipsis })
            }.width('100%').margin(5)
          }.width('100%')
        // ...
      }
      .width('100%')
      .height('100%')
      .padding({ left: 12, right: 12 })
    }
    // ...
  }
}

Sample Code