APL Text


The Text component displays text in either a single line or multiple lines.

Properties

The Text component has the following properties in addition to the base component properties. See the meaning of the columns.

Property Type Default Styled Dynamic Description

color

Color

depends on the theme

Yes

Yes

The color of the text.

fontFamily

String

sans-serif

Yes

Yes

Font family (such as "Amazon Ember Display").

fontSize

Non-negative absolute Dimension

40dp

Yes

Yes

The size of the text.

fontStyle

normal, italic

normal

Yes

Yes

The font style to display.

fontWeight

normal, bold, 100, 200, 300, 400, 500, 600, 700, 800, 900

normal

Yes

Yes

The font weight to display.

lang

String

""

Yes

Yes

The language of the text. When set, APL attempts to find a language-specific version of the fontFamily for displaying the text.

letterSpacing

Absolute Dimension

0

Yes

Yes

Additional space to add between letters.

lineHeight

Number (percentage)

125%

Yes

Yes

Line-height multiplier.

maxLines

Non-negative integer

0

Yes

Yes

The maximum number of lines of text to display. The text will be truncated with an ellipsis if not all text is visible.

onTextLayout

Array of command

[]

No

No

Commands to run when the text layout changes.

text

String

""

No

Yes

The markup to display in this text box. If this value is set to null or an empty string "", no content appears.

textAlign

auto, left, right, center, start, end

auto

Yes

Yes

Alignment of text within a paragraph.

textAlignVertical

auto, top, bottom, center

auto

Yes

Yes

Vertical alignment of text.

Most of these properties have default values specified by the current text style. Refer to Resources for a discussion of styles.

A Text component doesn't scroll unless it's within a ScrollView.

When the Text is the source or target of an event, the following values are reported in event.source or event.target:

{
  // Text-specific values
  "type": "Text",
  "text": String,      // Displayed text
  "color": Color,      // The text color

  // General component values
  "bind": Map,         // Access to component data-binding context
  "checked": Boolean,  // Checked state
  "disabled": Boolean, // Disabled state
  "focused": Boolean,  // Focused state
  "height": Number,    // Height of the component, in dp (includes the padding)
  "id": ID,            // ID of the component
  "opacity": Number,   // Opacity of the component [0-1]
  "pressed": Boolean,  // Pressed state
  "uid": UID,          // Runtime-generated unique ID of the component
  "width": Number      // Width of the component, in dp (includes the padding)
}

layoutDirection component property

The component layoutDirection property determines how the Text component interprets the textAlign property for aligning text.

height and width component properties

The component properties for height and width control the size of the bounding box for a Text component. When the bounding box is too small for the text to display, the device truncates the text and displays an ellipsis to indicate that not all text is displayed.

For details about the component height and width properties, see APL Base Component Properties.

For details and examples of the text bounding box, see Understand the bounding box for the Text component.

color

The color of the text. If the theme is light, the default is #1E2222. If the theme is dark, the default is #FAFAFA.

fontFamily

Specifies the font for the displayed text. The fontFamily property takes a single font name or a string containing a comma-separated list of font names. The APL runtime searches the list for the first named font installed on the device. If no valid font is found, the runtime defaults to the sans-serif font.

Font names can contain spaces. APL supports two types of font names:

  • The specific name of an installed font such as "amazon-ember", "times", "times new roman".
  • A generic name - either "serif" or "sans-serif".

Alexa devices don't guarantee a specific set of fonts. End your fontFamily list with either "serif" or "sans-serif" to make sure that a valid font is available.

{
"type": "Text",
"fontFamily", "times new roman, times, georgia, serif"
}

On many Alexa devices, "sans-serif" defaults to "Amazon Ember Display" and "serif" defaults to "Bookerly". In some Asian markets they default to "Noto Sans CJK".

For details about font styles available in the alexa-styles package, see Font family.

fontSize

The size of the font, normally expressed in dp. The default is 40dp.

fontStyle

The style of the font, either normal or italic. Defaults to normal.

fontWeight

The font weight for the displayed text. Defaults to normal. The normal and bold values are assigned at runtime. The integer values 100 through 900 correspond to progressively darker variations of the font. Most fonts don't support this many variations. For example, Amazon Ember Display has five weights (Thin, Light, Regular, Medium, Bold) which are assigned 100, 300, 500, 700, and 900 respectively.

Note that fontWeight represents an enumerated set, not integers or strings. For example, the value 750 is invalid and doesn't set the font to a weight between 700 and 800.

When you create a resource for a fontWeight, use a string resource. The following example resource block creates two resources for fontWeight called myMidFontWeight and myLightFontWeight.

{
  "resources": [
    {
      "strings": {
        "myMidFontWeight": "500",
        "myLightFontWeight": "100"
      }
    }
  ]
}

lang

The language of the text. When set, APL attempts to find a language-specific version of the fontFamily for displaying the text.

If no valid font is found, APL ignores this property and uses the specified fontFamily.

Set the lang property to a BCP-47 string (for example, "en-US").

The following example displays a Text component with a Japanese-style version of the NotoSans-CJK font:

{
    "type": "APL",
    "version": "2024.3",
    "mainTemplate": {
        "item": {
            "type": "Text",
            "lang": "ja-JP",
            "fontFamily": "Noto Sans CJK"
        }
    }
}

Note: Alexa devices might not have the font in specific language installed. Test the experience on the device or devices to confirm that it works.

letterSpacing

Additional space to add between letters. Defaults to 0.

lineHeight

Line-height multiplier. Defaults to 125%.

The leading of the font is the fontSize multiplied by the lineHeight. For example, on a 320 dpi display with 100dp fontSize and 120% lineHeight, the font size is 200 pixels and the leading is 240 pixels. Setting the lineHeight to less than 100% can cause characters to overlap.

maxLines

The maximum number of lines of text to display. Defaults to 0, which indicates no maximum. Set to a positive integer to clip the text to the specified number of lines and insert an ellipsis to show that the text is truncated.

onTextLayout

Commands to run when a text layout calculation for the component occurs.

For a Text component with a fixed size, the calculation doesn't affect component dimensions, so the handler runs after the component layout completes. For a Text component with auto for the size, the handler runs during the layout.

The commands defined in the handler can change text properties. In this scenario, only the resulting, final text is rendered.

The event.source.value is set to the standard source value for the component. Refer to Event source for a description of event.source properties.

The event generated has the following form.

"event": {
  "source": {
    "type": "Text",
    "handler": "TextLayout",
    ...                      // Component source properties
  },
  "laidOutText": STRING,  // Text which is actually laid out for display, accounting for clipping including ellipsis.
  "isTruncated": BOOLEAN, // True if text does not fit into requested binding box and was truncated.
  "textHeight": NUMBER,   // Measured height of the text in dp.
  "textWidth": NUMBER     // Measured width of the text in dp.
}

The following example uses a SetValue command in the onTextLayout event handler to reduce the fontSize on a Text component. The command runs when the text is truncated and the current font size is greater than ten. When the command reduces the fontSize, the text layout changes, so the onTextLayout handler is invoked again. This continues until either the text is no longer truncated, or the font size is ten or less.

Copied to clipboard.

{
  "type": "APL",
  "version": "2024.3",
  "theme": "dark",
  "import": [
    {
      "name": "alexa-layouts",
      "version": "1.7.0"
    }
  ],
  "mainTemplate": {
    "parameters": [
      "longTextContent"
    ],
    "items": [
      {
        "type": "Container",
        "height": "100%",
        "width": "100%",
        "padding": 16,
        "bind": [
          {
            "name": "FontSize",
            "value": 40
          },
          {
            "name": "TextToShow",
            "value": "${longTextContent.reallyLongText}"
          }
        ],
        "items": [
          {
            "type": "Text",
            "text": "Current fontSize: ${FontSize}, Characters: ${String.length(TextToShow)}<br>---"
          },
          {
            "type": "Text",
            "text": "${TextToShow}",
            "width": "100%",
            "height": "auto",
            "maxHeight": "50%",
            "fontSize": "${FontSize}",
            "onTextLayout": [
              {
                "when": "${event.isTruncated && event.source.bind.FontSize > 10}",
                "type": "SetValue",
                "property": "FontSize",
                "value": "${event.source.bind.FontSize - 10}"
              }
            ]
          }
        ]
      }
    ]
  }
}

Copied to clipboard.

{
  "longTextContent": {
    "reallyLongText": "This is a long block of text. The <code>maxHeight</code> property on the <code>Text</code> component restricts the component height to 50% of the parent <code>Container</code>. This long text doesn't all fit without truncating, so the <code>when</code> condition in the <code>onTextLayout</code> commands evaluates to true. The <code>SetValue</code> command shrinks the font by 10, which triggers the component to layout again.<br><br>This layout change triggers the <code>onTextLayout</code> again, and if the text is still truncated, we shrink the font size by 10 again. This process repeats until the <code>when</code> condition in the <code>onTextLayout</code> handler evaluates to <code>false</code>. The <code>when</code> condition ensures that the font size never goes below 10.<br><br>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Urna porttitor rhoncus dolor purus non enim. Porta nibh venenatis cras sed felis eget. Mauris pellentesque pulvinar pellentesque habitant morbi tristique senectus et netus. Dignissim convallis aenean et tortor. Purus semper eget duis at tellus at urna condimentum. Eros donec ac odio tempor orci dapibus ultrices in. Faucibus ornare suspendisse sed nisi lacus sed viverra. Sit amet mattis vulputate enim nulla aliquet porttitor lacus luctus. Egestas erat imperdiet sed euismod nisi porta. A condimentum vitae sapien pellentesque. Facilisi nullam vehicula ipsum a arcu cursus. Donec et odio pellentesque diam volutpat commodo. Enim tortor at auctor urna nunc.",
    "longText": "This is a long block of text. The <code>maxHeight</code> property on the <code>Text</code> component restricts the component height to 50% of the parent <code>Container</code>. This long text doesn't all fit without truncating, so the <code>when</code> condition in the <code>onTextLayout</code> commands evaluates to true. The <code>SetValue</code> command shrinks the font by 10, which triggers the component to layout again.<br><br>This layout change triggers the <code>onTextLayout</code> again, and if the text is still truncated, we shrink the font size by 10 again. This process repeats until the <code>when</code> condition in the <code>onTextLayout</code> handler evaluates to <code>false</code>. The <code>when</code> condition ensures that the font size never goes below 10.",
    "shortText": "This is a short block of text. The viewport displays the full text without truncating, so we use the 40 point font size."
  }
}

The onTextLayout event handler runs in fast mode in the component data-binding context.

text

Text string to display in the text block. If set to an empty string, no text displays. Setting to null is equivalent to an empty string ("").

Text blocks support simple markup. Supported tags include:

Tag Description Example Display

<br>

Insert a line break. Line breaks can be repeated.

Line 1<br>Line 2

Line 1
Line 2

<strong>, <b>

Bold a span of text. (font weight 700).

<b>Large</b> dogs are friendly.

Large dogs are friendly.

<em>, <i>

Italic a span of text.

Read <em>Emma</em> for homework.

Read Emma for homework.

<strike>

Strikethrough a span of text

The document is <strike>fine</strike> pretty good.

The document is fine pretty good.

<u>

Underline a span of text

I just <u>loved</u> the chocolate!

I just loved the chocolate!

<tt>, <code>

Monospace a span of text.

The <code>main</code> function is the entry point.

The main function is the entry point.

<sup>, <sub>

Superscript and subscript a span of text.

See Gibson<sup>1</sup> for the H<sub>2</sub>O formula.

See Gibson1 for the H2O formula.

<nobr>

Prevent text from automatically wrapping across multiple lines

Avoid breaking <nobr>Dr. A. Ramaswamy</nobr> and treat it as one whole word.

Avoid breaking
Dr. A. Ramaswamy and treat it as one whole word.

<span>

Define a span to apply inline formatting. For details, see Supported span attributes.

This is <span color="red">RED</span>

This is RED

<li>

Define a list item. For details, see List layouts.

Shopping list: <li>Bananas</li><li>Carrots</li>

Shopping list:

  • Bananas
  • Carrots

You can nest markup elements. Improperly nested markup gives undefined behavior. For example, the following code might not render correctly because the <b> and <u> elements aren't nested correctly.

<b>Once upon a time, <u>a small dog</b> ate a grasshopper and felt ill.</u>.

The following example shows the use of text markup.


Replace markup characters in text with character entity references.

Entity Character Description

&amp;

&

Ampersand

&lt;

<

Less-than

&gt;

>

Greater-than

&#nn;

Any Decimal Unicode code-point.

"nn" is a valid integer.

&#xnn;

Hexadecimal Unicode code-point.

"nn" is a valid hexadecimal number

Numeric entity references can be in decimal or hexadecimal. For example, © can be written &#169; or &#xa9;.

Supported span attributes

The <span> tag supports the named attributes shown in the following table.

Attribute Description Example Display

color

Color of the text span.

Can be any color. You can specify the color using a resource.

Set to inherit to set the span color to the color property of the text.

This is <span color="red">RED</span>

This is RED

fontSize

Font size for the text span. Must be a non-negative absolute dimension. You can set the dimension using a resource.

Set to inherit to set the font size of the span to the fontSize of the text.

This is <span fontSize="48dp"\>BIG</span\>

This is BIG

List layouts

APL supports bulleted list layouts. Any sequence of text blocks marked by <li> tags will be rendered as a bulleted list. Only flat bulleted lists are currently supported, any nested <li> tags will be flattened.

For example, the string "Shopping list:<li>Potatoes, preferably Yukon Gold, can substitute with Russet, as it's for the mash</li><li>Bananas<li>Carrots</li></li> also should not forget to get some pasta." renders as the following:

Shopping list:

  • Potatoes, preferably Yukon Gold, can substitute with Russet, as it's for the mash
  • Bananas
  • Carrots

also should not forget to get some pasta.

The list layout uses the Unicode symbol U+2022 (bullet ) as a marker. The padding and marker gap are equal to the whitespace width for the current font.

Copied to clipboard.

{
  "type": "APL",
  "version": "2024.3",
  "theme": "dark",
  "mainTemplate": {
    "parameters": [
      "payload"
    ],
    "items": [
      {
        "type": "Container",
        "height": "100%",
        "width": "100%",
        "padding": 20,
        "items": [
          {
            "type": "Text",
            "text": "Shopping list:<li>Potatoes, preferably Yukon Gold, can substitute with Russet, as it's for the mash</li><li>Bananas<li>Carrots</li></li> also should not forget to get some pasta."
          }
        ]
      }
    ]
  }
}

textAlign

Controls the horizontal alignment for lines of text. Set to one of the following:

  • auto (default)
  • left
  • center
  • right
  • start
  • end

The auto, start, and end properties all align the text based on the specified layoutDirection for the component:

Property Left-to-right ("LTR") Right-to-left ("RTL")

auto

Left-aligns text

Right-aligns text

start

Left-aligns text

Right-aligns text

end

Right-aligns text

Left-aligns text

The following example shows the different textAlign options and a button that cycles through the possible values for the property.

Copied to clipboard.

{
  "type": "APL",
  "version": "2024.3",
  "theme": "dark",
  "import": [
    {
      "name": "alexa-layouts",
      "version": "1.7.0"
    }
  ],
  "mainTemplate": {
    "parameters": [
      "payload"
    ],
    "items": [
      {
        "type": "Container",
        "id": "mainContainer",
        "height": "100%",
        "width": "100%",
        "bind": [
          {
            "name": "TextAlignSetting",
            "description": "Variable to store the textAlign property value; using a bind variable so that other components/commmands can have access to it.",
            "value": "auto"
          },
          {
            "name": "TAValues",
            "description": "Possible values for the textAlign property",
            "value": ["auto","center","right","left","end","start"]
          },
          {
            "name": "TACurrentIndex",
            "description": "Calculates the index of the selected textAlign setting within the TAValues array",
            "value": "${Array.indexOf(TAValues,TextAlignSetting)}"
          },
          {
            "name": "TANextValue",
            "description": "Uses the index of the selected setting to determine the next setting in the array. When at the end of the array, reset to the first item in the list (auto).",
            "value": "${TACurrentIndex < TAValues.length-1 ? TAValues[TACurrentIndex+1] : TAValues[0]}"
          }
        ],
        "items": [
          {
            "type": "AlexaHeader",
            "headerTitle": "textAlign Property Example"
          },
          {
            "type": "Text",
            "id": "myText",
            "height": "50%",
            "shrink": 1,
            "text": "This is the text to change.<br>The <code>textAlign</code> property is currently set to <b><code>${TextAlignSetting}</code></b>.",
            "paddingStart": "@marginHorizontal",
            "paddingEnd": "@marginHorizontal",
            "textAlign": "${TextAlignSetting}"
          },
          {
            "type": "AlexaButton",
            "buttonText": "Change textAlign to ${TANextValue}",
            "alignSelf": "center",
            "primaryAction": [
              {
                "type": "SetValue",
                "property": "TextAlignSetting",
                "value": "${TANextValue}"
              }
            ]
          }
        ]
      }
    ]
  }
}

textAlignVertical

Positions the text within the text box. Used when the text box is taller than the text content. Set to one of the following:

  • auto (default)
  • top
  • center
  • bottom

Defaults to auto, which uses the default font alignment. For English, the default font alignment is equivalent to top.

Sample text

The following example shows a Text component that displays the provided text in green. The example uses a conditional statement for the maxLines property to truncate the text on small, round hubs, but show the full text on larger devices.



Was this page helpful?

Last updated: Dec 18, 2024