androidx.compose.foundation.text

In this page, you'll find documentation for types, properties, and functions available in the androidx.compose.foundation.text package such as BasicText, BasicTextFiled, KeyboardActions, and KeyboardOptions.

If you're looking for guidance instead, check out the Text in Compose guide.

Interfaces

KeyboardActionScope

This scope can be used to execute the default action implementation.

Cmn

Classes

InlineTextContent

A data class that stores a composable to be inserted into the text layout.

Cmn
KeyboardActions

The KeyboardActions class allows developers to specify actions that will be triggered in response to users triggering IME action on the software keyboard.

Cmn
KeyboardOptions

The keyboard configuration options for TextFields.

Cmn

Annotations

Top-level functions summary

Unit
@ExperimentalFoundationApi
@Composable
BasicSecureTextField(
    state: TextFieldState,
    modifier: Modifier,
    onSubmit: ImeActionHandler?,
    imeAction: ImeAction,
    textObfuscationMode: TextObfuscationMode,
    keyboardType: KeyboardType,
    enabled: Boolean,
    inputTransformation: InputTransformation?,
    textStyle: TextStyle,
    interactionSource: MutableInteractionSource?,
    cursorBrush: Brush,
    onTextLayout: (Density.(getResult: () -> TextLayoutResult) -> Unit)?,
    decorator: TextFieldDecorator?,
    scrollState: ScrollState
)

BasicSecureTextField is specifically designed for password entry fields and is a preconfigured alternative to BasicTextField.

Cmn
Unit
@Composable
BasicText(
    text: String,
    modifier: Modifier,
    style: TextStyle,
    onTextLayout: ((TextLayoutResult) -> Unit)?,
    overflow: TextOverflow,
    softWrap: Boolean,
    maxLines: Int,
    minLines: Int,
    color: ColorProducer?
)

Basic element that displays text and provides semantics / accessibility information.

Cmn
Unit
@Composable
BasicText(
    text: AnnotatedString,
    modifier: Modifier,
    style: TextStyle,
    onTextLayout: ((TextLayoutResult) -> Unit)?,
    overflow: TextOverflow,
    softWrap: Boolean,
    maxLines: Int,
    minLines: Int,
    inlineContent: Map<StringInlineTextContent>,
    color: ColorProducer?
)

Basic element that displays text and provides semantics / accessibility information.

Cmn
Unit
@ExperimentalFoundationApi
@Composable
BasicText(
    text: AnnotatedString,
    modifier: Modifier,
    style: TextStyle,
    onTextLayout: ((TextLayoutResult) -> Unit)?,
    overflow: TextOverflow,
    softWrap: Boolean,
    maxLines: Int,
    minLines: Int,
    inlineContent: Map<StringInlineTextContent>,
    color: ColorProducer?,
    onLinkClicked: TextLinkClickHandler?
)

Basic element that displays text and provides semantics / accessibility information.

Cmn
Unit
@ExperimentalFoundationApi
@Composable
BasicTextField(
    state: TextFieldState,
    modifier: Modifier,
    enabled: Boolean,
    readOnly: Boolean,
    inputTransformation: InputTransformation?,
    textStyle: TextStyle,
    keyboardOptions: KeyboardOptions,
    keyboardActions: KeyboardActions,
    lineLimits: TextFieldLineLimits,
    onTextLayout: (Density.(getResult: () -> TextLayoutResult) -> Unit)?,
    interactionSource: MutableInteractionSource?,
    cursorBrush: Brush,
    outputTransformation: OutputTransformation?,
    decorator: TextFieldDecorator?,
    scrollState: ScrollState
)

Basic text composable that provides an interactive box that accepts text input through software or hardware keyboard, but provides no decorations like hint or placeholder.

Cmn
Unit
@Composable
BasicTextField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier,
    enabled: Boolean,
    readOnly: Boolean,
    textStyle: TextStyle,
    keyboardOptions: KeyboardOptions,
    keyboardActions: KeyboardActions,
    singleLine: Boolean,
    maxLines: Int,
    minLines: Int,
    visualTransformation: VisualTransformation,
    onTextLayout: (TextLayoutResult) -> Unit,
    interactionSource: MutableInteractionSource?,
    cursorBrush: Brush,
    decorationBox: @Composable (@Composable innerTextField: () -> Unit) -> Unit
)

Basic composable that enables users to edit text via hardware or software keyboard, but provides no decorations like hint or placeholder.

Cmn
Unit
@Composable
BasicTextField(
    value: TextFieldValue,
    onValueChange: (TextFieldValue) -> Unit,
    modifier: Modifier,
    enabled: Boolean,
    readOnly: Boolean,
    textStyle: TextStyle,
    keyboardOptions: KeyboardOptions,
    keyboardActions: KeyboardActions,
    singleLine: Boolean,
    maxLines: Int,
    minLines: Int,
    visualTransformation: VisualTransformation,
    onTextLayout: (TextLayoutResult) -> Unit,
    interactionSource: MutableInteractionSource?,
    cursorBrush: Brush,
    decorationBox: @Composable (@Composable innerTextField: () -> Unit) -> Unit
)

Basic composable that enables users to edit text via hardware or software keyboard, but provides no decorations like hint or placeholder.

Cmn
Unit
@Composable
ClickableText(
    text: AnnotatedString,
    modifier: Modifier,
    style: TextStyle,
    softWrap: Boolean,
    overflow: TextOverflow,
    maxLines: Int,
    onTextLayout: (TextLayoutResult) -> Unit,
    onClick: (Int) -> Unit
)

A continent version of BasicText component to be able to handle click event on the text.

Cmn
Unit
@ExperimentalFoundationApi
@Composable
ClickableText(
    text: AnnotatedString,
    onHover: (Int?) -> Unit,
    modifier: Modifier,
    style: TextStyle,
    softWrap: Boolean,
    overflow: TextOverflow,
    maxLines: Int,
    onTextLayout: (TextLayoutResult) -> Unit,
    onClick: (Int) -> Unit
)

A continent version of BasicText component to be able to handle click event on the text.

Cmn
KeyboardActions

Creates an instance of KeyboardActions that uses the specified lambda for all ImeActions.

Cmn

Extension functions summary

Unit
AnnotatedString.Builder.appendInlineContent(
    id: String,
    alternateText: String
)

Used to insert composables into the text layout.

Cmn

Top-level properties summary

ProvidableCompositionLocal<SpanStyle>

Composition local used to change the style used by text links in the hierarchy.

Cmn

Top-level functions

BasicSecureTextField

@ExperimentalFoundationApi
@Composable
fun BasicSecureTextField(
    state: TextFieldState,
    modifier: Modifier = Modifier,
    onSubmit: ImeActionHandler? = null,
    imeAction: ImeAction = ImeAction.Default,
    textObfuscationMode: TextObfuscationMode = TextObfuscationMode.RevealLastTyped,
    keyboardType: KeyboardType = KeyboardType.Password,
    enabled: Boolean = true,
    inputTransformation: InputTransformation? = null,
    textStyle: TextStyle = TextStyle.Default,
    interactionSource: MutableInteractionSource? = null,
    cursorBrush: Brush = SolidColor(Color.Black),
    onTextLayout: (Density.(getResult: () -> TextLayoutResult) -> Unit)? = null,
    decorator: TextFieldDecorator? = null,
    scrollState: ScrollState = rememberScrollState()
): Unit

BasicSecureTextField is specifically designed for password entry fields and is a preconfigured alternative to BasicTextField. It only supports a single line of content and comes with default settings for KeyboardOptions, InputTransformation, and CodepointTransformation that are appropriate for entering secure content. Additionally, some context menu actions like cut, copy, and drag are disabled for added security.

Parameters
state: TextFieldState

TextFieldState object that holds the internal state of a BasicTextField.

modifier: Modifier = Modifier

optional Modifier for this text field.

onSubmit: ImeActionHandler? = null

Called when the user submits a form either by pressing the action button in the input method editor (IME), or by pressing the enter key on a hardware keyboard. If the user submits the form by pressing the action button in the IME, the provided IME action is passed to the function. If the user submits the form by pressing the enter key on a hardware keyboard, the defined imeAction parameter is passed to the function. Return true to indicate that the action has been handled completely, which will skip the default behavior, such as hiding the keyboard for the ImeAction.Done action.

imeAction: ImeAction = ImeAction.Default

The IME action. This IME action is honored by keyboard and may show specific icons on the keyboard.

textObfuscationMode: TextObfuscationMode = TextObfuscationMode.RevealLastTyped

Determines the method used to obscure the input text.

keyboardType: KeyboardType = KeyboardType.Password

The keyboard type to be used in this text field. It is set to KeyboardType.Password by default. Use KeyboardType.NumberPassword for numerical password fields.

enabled: Boolean = true

controls the enabled state of the BasicTextField. When false, the text field will be neither editable nor focusable, the input of the text field will not be selectable.

inputTransformation: InputTransformation? = null

Optional InputTransformation that will be used to transform changes to the TextFieldState made by the user. The transformation will be applied to changes made by hardware and software keyboard events, pasting or dropping text, accessibility services, and tests. The transformation will not be applied when changing the state programmatically, or when the transformation is changed. If the transformation is changed on an existing text field, it will be applied to the next user edit. The transformation will not immediately affect the current state.

textStyle: TextStyle = TextStyle.Default

Style configuration for text content that's displayed in the editor.

interactionSource: MutableInteractionSource? = null

the MutableInteractionSource representing the stream of Interactions for this TextField. You can create and pass in your own remembered MutableInteractionSource if you want to observe Interactions and customize the appearance / behavior of this TextField for different Interactions.

cursorBrush: Brush = SolidColor(Color.Black)

Brush to paint cursor with. If SolidColor with Color.Unspecified provided, there will be no cursor drawn.

onTextLayout: (Density.(getResult: () -> TextLayoutResult) -> Unit)? = null

Callback that is executed when the text layout becomes queryable. The callback receives a function that returns a TextLayoutResult if the layout can be calculated, or null if it cannot. The function reads the layout result from a snapshot state object, and will invalidate its caller when the layout result changes. A TextLayoutResult object contains paragraph information, size of the text, baselines and other details. The callback can be used to add additional decoration or functionality to the text. For example, to draw a cursor or selection around the text. Density scope is the one that was used while creating the given text layout.

decorator: TextFieldDecorator? = null

Allows to add decorations around text field, such as icon, placeholder, helper messages or similar, and automatically increase the hit target area of the text field.

scrollState: ScrollState = rememberScrollState()

Used to manage the horizontal scroll when the input content exceeds the bounds of the text field. It controls the state of the scroll for the text field.

@Composable
fun BasicText(
    text: String,
    modifier: Modifier = Modifier,
    style: TextStyle = TextStyle.Default,
    onTextLayout: ((TextLayoutResult) -> Unit)? = null,
    overflow: TextOverflow = TextOverflow.Clip,
    softWrap: Boolean = true,
    maxLines: Int = Int.MAX_VALUE,
    minLines: Int = 1,
    color: ColorProducer? = null
): Unit

Basic element that displays text and provides semantics / accessibility information. Typically you will instead want to use androidx.compose.material.Text, which is a higher level Text element that contains semantics and consumes style information from a theme.

Parameters
text: String

The text to be displayed.

modifier: Modifier = Modifier

Modifier to apply to this layout node.

style: TextStyle = TextStyle.Default

Style configuration for the text such as color, font, line height etc.

onTextLayout: ((TextLayoutResult) -> Unit)? = null

Callback that is executed when a new text layout is calculated. A TextLayoutResult object that callback provides contains paragraph information, size of the text, baselines and other details. The callback can be used to add additional decoration or functionality to the text. For example, to draw selection around the text.

overflow: TextOverflow = TextOverflow.Clip

How visual overflow should be handled.

softWrap: Boolean = true

Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If softWrap is false, overflow and TextAlign may have unexpected effects.

maxLines: Int = Int.MAX_VALUE

An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow and softWrap. It is required that 1 <= minLines<= maxLines.

minLines: Int = 1

The minimum height in terms of minimum number of visible lines. It is required that 1 <= minLines<= maxLines.

color: ColorProducer? = null

Overrides the text color provided in style

@Composable
fun BasicText(
    text: AnnotatedString,
    modifier: Modifier = Modifier,
    style: TextStyle = TextStyle.Default,
    onTextLayout: ((TextLayoutResult) -> Unit)? = null,
    overflow: TextOverflow = TextOverflow.Clip,
    softWrap: Boolean = true,
    maxLines: Int = Int.MAX_VALUE,
    minLines: Int = 1,
    inlineContent: Map<StringInlineTextContent> = mapOf(),
    color: ColorProducer? = null
): Unit

Basic element that displays text and provides semantics / accessibility information. Typically you will instead want to use androidx.compose.material.Text, which is a higher level Text element that contains semantics and consumes style information from a theme.

Parameters
text: AnnotatedString

The text to be displayed.

modifier: Modifier = Modifier

Modifier to apply to this layout node.

style: TextStyle = TextStyle.Default

Style configuration for the text such as color, font, line height etc.

onTextLayout: ((TextLayoutResult) -> Unit)? = null

Callback that is executed when a new text layout is calculated. A TextLayoutResult object that callback provides contains paragraph information, size of the text, baselines and other details. The callback can be used to add additional decoration or functionality to the text. For example, to draw selection around the text.

overflow: TextOverflow = TextOverflow.Clip

How visual overflow should be handled.

softWrap: Boolean = true

Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If softWrap is false, overflow and TextAlign may have unexpected effects.

maxLines: Int = Int.MAX_VALUE

An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow and softWrap. It is required that 1 <= minLines<= maxLines.

minLines: Int = 1

The minimum height in terms of minimum number of visible lines. It is required that 1 <= minLines<= maxLines.

inlineContent: Map<StringInlineTextContent> = mapOf()

A map store composables that replaces certain ranges of the text. It's used to insert composables into text layout. Check InlineTextContent for more information.

color: ColorProducer? = null

Overrides the text color provided in style

@ExperimentalFoundationApi
@Composable
fun BasicText(
    text: AnnotatedString,
    modifier: Modifier = Modifier,
    style: TextStyle = TextStyle.Default,
    onTextLayout: ((TextLayoutResult) -> Unit)? = null,
    overflow: TextOverflow = TextOverflow.Clip,
    softWrap: Boolean = true,
    maxLines: Int = Int.MAX_VALUE,
    minLines: Int = 1,
    inlineContent: Map<StringInlineTextContent> = mapOf(),
    color: ColorProducer? = null,
    onLinkClicked: TextLinkClickHandler? = null
): Unit

Basic element that displays text and provides semantics / accessibility information. Typically you will instead want to use androidx.compose.material.Text, which is a higher level Text element that contains semantics and consumes style information from a theme.

To display hyperlinks in text, see example below

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.text.BasicText
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withAnnotation

Column {
    BasicText(buildAnnotatedString {
        withAnnotation(LinkAnnotation.Url("https://developer.android.com/")) {
            append("Android for Developers")
        }
    })

    @OptIn(ExperimentalFoundationApi::class)
    BasicText(
        text = buildAnnotatedString {
            append("Click ")
            withAnnotation(LinkAnnotation.Clickable("tag")) {
                append("here")
            }
        },
        onLinkClicked = {
            // do something with link
        }
    )
}
Parameters
text: AnnotatedString

The text to be displayed.

modifier: Modifier = Modifier

Modifier to apply to this layout node.

style: TextStyle = TextStyle.Default

Style configuration for the text such as color, font, line height etc.

onTextLayout: ((TextLayoutResult) -> Unit)? = null

Callback that is executed when a new text layout is calculated. A TextLayoutResult object that callback provides contains paragraph information, size of the text, baselines and other details. The callback can be used to add additional decoration or functionality to the text. For example, to draw selection around the text.

overflow: TextOverflow = TextOverflow.Clip

How visual overflow should be handled.

softWrap: Boolean = true

Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If softWrap is false, overflow and TextAlign may have unexpected effects.

maxLines: Int = Int.MAX_VALUE

An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow and softWrap. It is required that 1 <= minLines<= maxLines.

minLines: Int = 1

The minimum height in terms of minimum number of visible lines. It is required that 1 <= minLines<= maxLines.

inlineContent: Map<StringInlineTextContent> = mapOf()

A map store composables that replaces certain ranges of the text. It's used to insert composables into text layout. Check InlineTextContent for more information.

color: ColorProducer? = null

Overrides the text color provided in style

onLinkClicked: TextLinkClickHandler? = null

a handler that is called when a (link)androidx.compose.ui.text.LinkAnnotation inside the text is clicked. If you need to make part of a text clickable, you can mark that part as a (Url)androidx.compose.ui.text.LinkAnnotation.Url or (Clickable)androidx.compose.ui.text.LinkAnnotation.Clickable. When a user will click on it, this handler will be triggered. Note that when null is passed, a default link handling mechanism will be triggered. Which is for (Url)androidx.compose.ui.text.LinkAnnotation.Url the system will try to open the corresponding url and for (Clickable)androidx.compose.ui.text.LinkAnnotation.Clickable it will be a no-op.

BasicTextField

@ExperimentalFoundationApi
@Composable
fun BasicTextField(
    state: TextFieldState,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    inputTransformation: InputTransformation? = null,
    textStyle: TextStyle = TextStyle.Default,
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
    keyboardActions: KeyboardActions = KeyboardActions.Default,
    lineLimits: TextFieldLineLimits = TextFieldLineLimits.Default,
    onTextLayout: (Density.(getResult: () -> TextLayoutResult) -> Unit)? = null,
    interactionSource: MutableInteractionSource? = null,
    cursorBrush: Brush = SolidColor(Color.Black),
    outputTransformation: OutputTransformation? = null,
    decorator: TextFieldDecorator? = null,
    scrollState: ScrollState = rememberScrollState()
): Unit

Basic text composable that provides an interactive box that accepts text input through software or hardware keyboard, but provides no decorations like hint or placeholder.

All the editing state of this composable is hoisted through state. Whenever the contents of this composable change via user input or semantics, TextFieldState.text gets updated. Similarly, all the programmatic updates made to state also reflect on this composable.

If you want to add decorations to your text field, such as icon or similar, and increase the hit target area, use the decorator:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.material.Icon

val state = rememberTextFieldState("Hello, World!")
BasicTextField(
    state = state,
    decorator = { innerTextField ->
        // Because the decorator is used, the whole Row gets the same behaviour as the internal
        // input field would have otherwise. For example, there is no need to add a
        // `Modifier.clickable` to the Row anymore to bring the text field into focus when user
        // taps on a larger text field area which includes paddings and the icon areas.
        Row(
            Modifier
                .background(Color.LightGray, RoundedCornerShape(percent = 30))
                .padding(16.dp)
        ) {
            Icon(Icons.Default.MailOutline, contentDescription = "Mail Icon")
            Spacer(Modifier.width(16.dp))
            innerTextField()
        }
    }
)

In order to filter (e.g. only allow digits, limit the number of characters), or change (e.g. convert every character to uppercase) the input received from the user, use an InputTransformation.

import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.input.TextFieldState
import androidx.compose.foundation.text.input.delete
import androidx.compose.foundation.text.input.insert
import androidx.compose.runtime.remember

val state = remember { TextFieldState() }
BasicTextField(state, inputTransformation = { _, new ->
    // A filter that always places newly-input text at the start of the string, after a
    // prompt character, like a shell.
    val promptChar = '>'

    fun CharSequence.countPrefix(char: Char): Int {
        var i = 0
        while (i < length && get(i) == char) i++
        return i
    }

    // Step one: Figure out the insertion point.
    val newPromptChars = new.asCharSequence().countPrefix(promptChar)
    val insertionPoint = if (newPromptChars == 0) 0 else 1

    // Step two: Ensure text is placed at the insertion point.
    if (new.changes.changeCount == 1) {
        val insertedRange = new.changes.getRange(0)
        val replacedRange = new.changes.getOriginalRange(0)
        if (!replacedRange.collapsed && insertedRange.collapsed) {
            // Text was deleted, delete forwards from insertion point.
            new.delete(insertionPoint, insertionPoint + replacedRange.length)
        }
    }
    // Else text was replaced or there were multiple changes - don't handle.

    // Step three: Ensure the prompt character is there.
    if (newPromptChars == 0) {
        new.insert(0, ">")
    }

    // Step four: Ensure the cursor is ready for the next input.
    new.placeCursorAfterCharAt(0)
})

Limiting the height of the BasicTextField in terms of line count and choosing a scroll direction can be achieved by using TextFieldLineLimits.

Scroll state of the composable is also hoisted to enable observation and manipulation of the scroll behavior by the developer, e.g. bringing a searched keyword into view by scrolling to its position without focusing, or changing selection.

It's also possible to internally wrap around an existing TextFieldState and expose a more lightweight state hoisting mechanism through a value that dictates the content of the TextField and an onValueChange callback that communicates the changes to this value.

import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember

var text by remember { mutableStateOf("") }
StringTextField(
    value = text,
    onValueChange = { text = it }
)
Parameters
state: TextFieldState

TextFieldState object that holds the internal editing state of BasicTextField.

modifier: Modifier = Modifier

optional Modifier for this text field.

enabled: Boolean = true

controls the enabled state of the BasicTextField. When false, the text field will be neither editable nor focusable, the input of the text field will not be selectable.

readOnly: Boolean = false

controls the editable state of the BasicTextField. When true, the text field can not be modified, however, a user can focus it and copy text from it. Read-only text fields are usually used to display pre-filled forms that user can not edit.

inputTransformation: InputTransformation? = null

Optional InputTransformation that will be used to transform changes to the TextFieldState made by the user. The transformation will be applied to changes made by hardware and software keyboard events, pasting or dropping text, accessibility services, and tests. The transformation will not be applied when changing the state programmatically, or when the transformation is changed. If the transformation is changed on an existing text field, it will be applied to the next user edit. the transformation will not immediately affect the current state.

textStyle: TextStyle = TextStyle.Default

Typographic and graphic style configuration for text content that's displayed in the editor.

keyboardOptions: KeyboardOptions = KeyboardOptions.Default

Software keyboard options that contain configurations such as KeyboardType and ImeAction.

keyboardActions: KeyboardActions = KeyboardActions.Default

When the input service emits an IME action, the corresponding callback is called. Note that this IME action may be different from what you specified in KeyboardOptions.imeAction.

lineLimits: TextFieldLineLimits = TextFieldLineLimits.Default

Whether the text field should be SingleLine, scroll horizontally, and ignore newlines; or MultiLine and grow and scroll vertically. If SingleLine is passed, all newline characters ('\n') within the text will be replaced with regular whitespace (' '), ensuring that the contents of the text field are presented in a single line.

onTextLayout: (Density.(getResult: () -> TextLayoutResult) -> Unit)? = null

Callback that is executed when the text layout becomes queryable. The callback receives a function that returns a TextLayoutResult if the layout can be calculated, or null if it cannot. The function reads the layout result from a snapshot state object, and will invalidate its caller when the layout result changes. A TextLayoutResult object contains paragraph information, size of the text, baselines and other details. The callback can be used to add additional decoration or functionality to the text. For example, to draw a cursor or selection around the text. Density scope is the one that was used while creating the given text layout.

interactionSource: MutableInteractionSource? = null

the MutableInteractionSource representing the stream of Interactions for this TextField. You can create and pass in your own remembered MutableInteractionSource if you want to observe Interactions and customize the appearance / behavior of this TextField for different Interactions.

cursorBrush: Brush = SolidColor(Color.Black)

Brush to paint cursor with. If SolidColor with Color.Unspecified provided, then no cursor will be drawn.

outputTransformation: OutputTransformation? = null

An OutputTransformation that transforms how the contents of the text field are presented.

decorator: TextFieldDecorator? = null

Allows to add decorations around text field, such as icon, placeholder, helper messages or similar, and automatically increase the hit target area of the text field.

scrollState: ScrollState = rememberScrollState()

Scroll state that manages either horizontal or vertical scroll of TextField. If lineLimits is SingleLine, this text field is treated as single line with horizontal scroll behavior. In other cases the text field becomes vertically scrollable.

BasicTextField

@Composable
fun BasicTextField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    textStyle: TextStyle = TextStyle.Default,
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
    keyboardActions: KeyboardActions = KeyboardActions.Default,
    singleLine: Boolean = false,
    maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE,
    minLines: Int = 1,
    visualTransformation: VisualTransformation = VisualTransformation.None,
    onTextLayout: (TextLayoutResult) -> Unit = {},
    interactionSource: MutableInteractionSource? = null,
    cursorBrush: Brush = SolidColor(Color.Black),
    decorationBox: @Composable (@Composable innerTextField: () -> Unit) -> Unit = @Composable { innerTextField -> innerTextField() }
): Unit

Basic composable that enables users to edit text via hardware or software keyboard, but provides no decorations like hint or placeholder.

Whenever the user edits the text, onValueChange is called with the most up to date state represented by String with which developer is expected to update their state.

Unlike TextFieldValue overload, this composable does not let the developer control selection, cursor and text composition information. Please check TextFieldValue and corresponding BasicTextField overload for more information.

It is crucial that the value provided to the onValueChange is fed back into BasicTextField in order to actually display and continue to edit that text in the field. The value you feed back into the field may be different than the one provided to the onValueChange callback, however the following caveats apply:

  • The new value must be provided to BasicTextField immediately (i.e. by the next frame), or the text field may appear to glitch, e.g. the cursor may jump around. For more information about this requirement, see this article.

  • The value fed back into the field may be different from the one passed to onValueChange, although this may result in the input connection being restarted, which can make the keyboard flicker for the user. This is acceptable when you're using the callback to, for example, filter out certain types of input, but should probably not be done on every update when entering freeform text.

This composable provides basic text editing functionality, however does not include any decorations such as borders, hints/placeholder. A design system based implementation such as Material Design Filled text field is typically what is needed to cover most of the needs. This composable is designed to be used when a custom implementation for different design system is needed.

Example usage:

import androidx.compose.foundation.text.BasicTextField
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable

var value by rememberSaveable { mutableStateOf("initial value") }
BasicTextField(
    value = value,
    onValueChange = {
        // it is crucial that the update is fed back into BasicTextField in order to
        // see updates on the text
        value = it
    }
)

For example, if you need to include a placeholder in your TextField, you can write a composable using the decoration box like this:

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable

var value by rememberSaveable { mutableStateOf("initial value") }
Box {
    BasicTextField(
        value = value,
        onValueChange = { value = it }
    )
    if (value.isEmpty()) {
        Text(text = "Placeholder")
    }
}

If you want to add decorations to your text field, such as icon or similar, and increase the hit target area, use the decoration box:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.Icon
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable

var value by rememberSaveable { mutableStateOf("initial value") }
BasicTextField(
    value = value,
    onValueChange = { value = it },
    decorationBox = { innerTextField ->
        // Because the decorationBox is used, the whole Row gets the same behaviour as the
        // internal input field would have otherwise. For example, there is no need to add a
        // Modifier.clickable to the Row anymore to bring the text field into focus when user
        // taps on a larger text field area which includes paddings and the icon areas.
        Row(
            Modifier
                .background(Color.LightGray, RoundedCornerShape(percent = 30))
                .padding(16.dp)
        ) {
            Icon(Icons.Default.MailOutline, contentDescription = null)
            Spacer(Modifier.width(16.dp))
            innerTextField()
        }
    }
)

In order to create formatted text field, for example for entering a phone number or a social security number, use a visualTransformation parameter. Below is the example of the text field for entering a credit card number:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.substring

/** The offset translator used for credit card input field */
val creditCardOffsetTranslator = object : OffsetMapping {
    override fun originalToTransformed(offset: Int): Int {
        return when {
            offset < 4 -> offset
            offset < 8 -> offset + 1
            offset < 12 -> offset + 2
            offset <= 16 -> offset + 3
            else -> 19
        }
    }

    override fun transformedToOriginal(offset: Int): Int {
        return when {
            offset <= 4 -> offset
            offset <= 9 -> offset - 1
            offset <= 14 -> offset - 2
            offset <= 19 -> offset - 3
            else -> 16
        }
    }
}

/**
 * Converts up to 16 digits to hyphen connected 4 digits string. For example,
 * "1234567890123456" will be shown as "1234-5678-9012-3456"
 */
val creditCardTransformation = VisualTransformation { text ->
    val trimmedText = if (text.text.length > 16) text.text.substring(0..15) else text.text
    var transformedText = ""
    trimmedText.forEachIndexed { index, char ->
        transformedText += char
        if ((index + 1) % 4 == 0 && index != 15) transformedText += "-"
    }
    TransformedText(AnnotatedString(transformedText), creditCardOffsetTranslator)
}

var text by rememberSaveable { mutableStateOf("") }
BasicTextField(
    value = text,
    onValueChange = { input ->
        if (input.length <= 16 && input.none { !it.isDigit() }) {
            text = input
        }
    },
    modifier = Modifier.size(170.dp, 30.dp).background(Color.LightGray).wrapContentSize(),
    singleLine = true,
    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
    visualTransformation = creditCardTransformation
)

Note: This overload does not support KeyboardOptions.shouldShowKeyboardOnFocus.

Parameters
value: String

the input String text to be shown in the text field

onValueChange: (String) -> Unit

the callback that is triggered when the input service updates the text. An updated text comes as a parameter of the callback

modifier: Modifier = Modifier

optional Modifier for this text field.

enabled: Boolean = true

controls the enabled state of the BasicTextField. When false, the text field will be neither editable nor focusable, the input of the text field will not be selectable

readOnly: Boolean = false

controls the editable state of the BasicTextField. When true, the text field can not be modified, however, a user can focus it and copy text from it. Read-only text fields are usually used to display pre-filled forms that user can not edit

textStyle: TextStyle = TextStyle.Default

Style configuration that applies at character level such as color, font etc.

keyboardOptions: KeyboardOptions = KeyboardOptions.Default

software keyboard options that contains configuration such as KeyboardType and ImeAction.

keyboardActions: KeyboardActions = KeyboardActions.Default

when the input service emits an IME action, the corresponding callback is called. Note that this IME action may be different from what you specified in KeyboardOptions.imeAction.

singleLine: Boolean = false

when set to true, this text field becomes a single horizontally scrolling text field instead of wrapping onto multiple lines. The keyboard will be informed to not show the return key as the ImeAction. maxLines and minLines are ignored as both are automatically set to 1.

maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE

the maximum height in terms of maximum number of visible lines. It is required that 1 <= minLines<= maxLines. This parameter is ignored when singleLine is true.

minLines: Int = 1

the minimum height in terms of minimum number of visible lines. It is required that 1 <= minLines<= maxLines. This parameter is ignored when singleLine is true.

visualTransformation: VisualTransformation = VisualTransformation.None

The visual transformation filter for changing the visual representation of the input. By default no visual transformation is applied.

onTextLayout: (TextLayoutResult) -> Unit = {}

Callback that is executed when a new text layout is calculated. A TextLayoutResult object that callback provides contains paragraph information, size of the text, baselines and other details. The callback can be used to add additional decoration or functionality to the text. For example, to draw a cursor or selection around the text.

interactionSource: MutableInteractionSource? = null

an optional hoisted MutableInteractionSource for observing and emitting Interactions for this text field. You can use this to change the text field's appearance or preview the text field in different states. Note that if null is provided, interactions will still happen internally.

cursorBrush: Brush = SolidColor(Color.Black)

Brush to paint cursor with. If SolidColor with Color.Unspecified provided, there will be no cursor drawn

decorationBox: @Composable (@Composable innerTextField: () -> Unit) -> Unit = @Composable { innerTextField -> innerTextField() }

Composable lambda that allows to add decorations around text field, such as icon, placeholder, helper messages or similar, and automatically increase the hit target area of the text field. To allow you to control the placement of the inner text field relative to your decorations, the text field implementation will pass in a framework-controlled composable parameter "innerTextField" to the decorationBox lambda you provide. You must call innerTextField exactly once.

BasicTextField

@Composable
fun BasicTextField(
    value: TextFieldValue,
    onValueChange: (TextFieldValue) -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    textStyle: TextStyle = TextStyle.Default,
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
    keyboardActions: KeyboardActions = KeyboardActions.Default,
    singleLine: Boolean = false,
    maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE,
    minLines: Int = 1,
    visualTransformation: VisualTransformation = VisualTransformation.None,
    onTextLayout: (TextLayoutResult) -> Unit = {},
    interactionSource: MutableInteractionSource? = null,
    cursorBrush: Brush = SolidColor(Color.Black),
    decorationBox: @Composable (@Composable innerTextField: () -> Unit) -> Unit = @Composable { innerTextField -> innerTextField() }
): Unit

Basic composable that enables users to edit text via hardware or software keyboard, but provides no decorations like hint or placeholder.

Whenever the user edits the text, onValueChange is called with the most up to date state represented by TextFieldValue. TextFieldValue contains the text entered by user, as well as selection, cursor and text composition information. Please check TextFieldValue for the description of its contents.

It is crucial that the value provided to the onValueChange is fed back into BasicTextField in order to actually display and continue to edit that text in the field. The value you feed back into the field may be different than the one provided to the onValueChange callback, however the following caveats apply:

  • The new value must be provided to BasicTextField immediately (i.e. by the next frame), or the text field may appear to glitch, e.g. the cursor may jump around. For more information about this requirement, see this article.

  • The value fed back into the field may be different from the one passed to onValueChange, although this may result in the input connection being restarted, which can make the keyboard flicker for the user. This is acceptable when you're using the callback to, for example, filter out certain types of input, but should probably not be done on every update when entering freeform text.

This composable provides basic text editing functionality, however does not include any decorations such as borders, hints/placeholder. A design system based implementation such as Material Design Filled text field is typically what is needed to cover most of the needs. This composable is designed to be used when a custom implementation for different design system is needed.

Example usage:

import androidx.compose.foundation.text.BasicTextField
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.text.input.TextFieldValue

var value by rememberSaveable(stateSaver = TextFieldValue.Saver) {
    mutableStateOf(TextFieldValue())
}
BasicTextField(
    value = value,
    onValueChange = {
        // it is crucial that the update is fed back into BasicTextField in order to
        // see updates on the text
        value = it
    }
)

For example, if you need to include a placeholder in your TextField, you can write a composable using the decoration box like this:

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable

var value by rememberSaveable { mutableStateOf("initial value") }
Box {
    BasicTextField(
        value = value,
        onValueChange = { value = it }
    )
    if (value.isEmpty()) {
        Text(text = "Placeholder")
    }
}

If you want to add decorations to your text field, such as icon or similar, and increase the hit target area, use the decoration box:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.Icon
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable

var value by rememberSaveable { mutableStateOf("initial value") }
BasicTextField(
    value = value,
    onValueChange = { value = it },
    decorationBox = { innerTextField ->
        // Because the decorationBox is used, the whole Row gets the same behaviour as the
        // internal input field would have otherwise. For example, there is no need to add a
        // Modifier.clickable to the Row anymore to bring the text field into focus when user
        // taps on a larger text field area which includes paddings and the icon areas.
        Row(
            Modifier
                .background(Color.LightGray, RoundedCornerShape(percent = 30))
                .padding(16.dp)
        ) {
            Icon(Icons.Default.MailOutline, contentDescription = null)
            Spacer(Modifier.width(16.dp))
            innerTextField()
        }
    }
)

Note: This overload does not support KeyboardOptions.shouldShowKeyboardOnFocus.

Parameters
value: TextFieldValue

The androidx.compose.ui.text.input.TextFieldValue to be shown in the BasicTextField.

onValueChange: (TextFieldValue) -> Unit

Called when the input service updates the values in TextFieldValue.

modifier: Modifier = Modifier

optional Modifier for this text field.

enabled: Boolean = true

controls the enabled state of the BasicTextField. When false, the text field will be neither editable nor focusable, the input of the text field will not be selectable

readOnly: Boolean = false

controls the editable state of the BasicTextField. When true, the text field can not be modified, however, a user can focus it and copy text from it. Read-only text fields are usually used to display pre-filled forms that user can not edit

textStyle: TextStyle = TextStyle.Default

Style configuration that applies at character level such as color, font etc.

keyboardOptions: KeyboardOptions = KeyboardOptions.Default

software keyboard options that contains configuration such as KeyboardType and ImeAction.

keyboardActions: KeyboardActions = KeyboardActions.Default

when the input service emits an IME action, the corresponding callback is called. Note that this IME action may be different from what you specified in KeyboardOptions.imeAction.

singleLine: Boolean = false

when set to true, this text field becomes a single horizontally scrolling text field instead of wrapping onto multiple lines. The keyboard will be informed to not show the return key as the ImeAction. maxLines and minLines are ignored as both are automatically set to 1.

maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE

the maximum height in terms of maximum number of visible lines. It is required that 1 <= minLines<= maxLines. This parameter is ignored when singleLine is true.

minLines: Int = 1

the minimum height in terms of minimum number of visible lines. It is required that 1 <= minLines<= maxLines. This parameter is ignored when singleLine is true.

visualTransformation: VisualTransformation = VisualTransformation.None

The visual transformation filter for changing the visual representation of the input. By default no visual transformation is applied.

onTextLayout: (TextLayoutResult) -> Unit = {}

Callback that is executed when a new text layout is calculated. A TextLayoutResult object that callback provides contains paragraph information, size of the text, baselines and other details. The callback can be used to add additional decoration or functionality to the text. For example, to draw a cursor or selection around the text.

interactionSource: MutableInteractionSource? = null

an optional hoisted MutableInteractionSource for observing and emitting Interactions for this text field. You can use this to change the text field's appearance or preview the text field in different states. Note that if null is provided, interactions will still happen internally.

cursorBrush: Brush = SolidColor(Color.Black)

Brush to paint cursor with. If SolidColor with Color.Unspecified provided, there will be no cursor drawn

decorationBox: @Composable (@Composable innerTextField: () -> Unit) -> Unit = @Composable { innerTextField -> innerTextField() }

Composable lambda that allows to add decorations around text field, such as icon, placeholder, helper messages or similar, and automatically increase the hit target area of the text field. To allow you to control the placement of the inner text field relative to your decorations, the text field implementation will pass in a framework-controlled composable parameter "innerTextField" to the decorationBox lambda you provide. You must call innerTextField exactly once.

@Composable
fun ClickableText(
    text: AnnotatedString,
    modifier: Modifier = Modifier,
    style: TextStyle = TextStyle.Default,
    softWrap: Boolean = true,
    overflow: TextOverflow = TextOverflow.Clip,
    maxLines: Int = Int.MAX_VALUE,
    onTextLayout: (TextLayoutResult) -> Unit = {},
    onClick: (Int) -> Unit
): Unit

A continent version of BasicText component to be able to handle click event on the text.

This is a shorthand of BasicText with pointerInput to be able to handle click event easily.

import androidx.compose.foundation.text.ClickableText
import androidx.compose.ui.text.AnnotatedString

ClickableText(
    text = AnnotatedString("Click Me"),
    onClick = { offset ->
        Log.d("ClickableText", "$offset -th character is clicked.")
    }
)

For other gestures, e.g. long press, dragging, follow sample code.

import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.input.pointer.pointerInput

val layoutResult = remember { mutableStateOf<TextLayoutResult?>(null) }
val gesture = Modifier.pointerInput(onLongClick) {
    detectTapGestures(
        onLongPress = { pos ->
            layoutResult.value?.let { layout ->
                onLongClick(layout.getOffsetForPosition(pos))
            }
        }
    )
}

Text(
    text = text,
    modifier = modifier.then(gesture),
    style = style,
    softWrap = softWrap,
    overflow = overflow,
    maxLines = maxLines,
    onTextLayout = {
        onTextLayout(it)
        layoutResult.value = it
    }
)
Parameters
text: AnnotatedString

The text to be displayed.

modifier: Modifier = Modifier

Modifier to apply to this layout node.

style: TextStyle = TextStyle.Default

Style configuration for the text such as color, font, line height etc.

softWrap: Boolean = true

Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If softWrap is false, overflow and TextAlign may have unexpected effects.

overflow: TextOverflow = TextOverflow.Clip

How visual overflow should be handled.

maxLines: Int = Int.MAX_VALUE

An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow and softWrap. If it is not null, then it must be greater than zero.

onTextLayout: (TextLayoutResult) -> Unit = {}

Callback that is executed when a new text layout is calculated. A TextLayoutResult object that callback provides contains paragraph information, size of the text, baselines and other details. The callback can be used to add additional decoration or functionality to the text. For example, to draw selection around the text.

onClick: (Int) -> Unit

Callback that is executed when users click the text. This callback is called with clicked character's offset.

@ExperimentalFoundationApi
@Composable
fun ClickableText(
    text: AnnotatedString,
    onHover: (Int?) -> Unit,
    modifier: Modifier = Modifier,
    style: TextStyle = TextStyle.Default,
    softWrap: Boolean = true,
    overflow: TextOverflow = TextOverflow.Clip,
    maxLines: Int = Int.MAX_VALUE,
    onTextLayout: (TextLayoutResult) -> Unit = {},
    onClick: (Int) -> Unit
): Unit

A continent version of BasicText component to be able to handle click event on the text.

This is a shorthand of BasicText with pointerInput to be able to handle click event easily.

import androidx.compose.foundation.text.ClickableText
import androidx.compose.ui.text.AnnotatedString

ClickableText(
    text = AnnotatedString("Click Me"),
    onClick = { offset ->
        Log.d("ClickableText", "$offset -th character is clicked.")
    }
)

For other gestures, e.g. long press, dragging, follow sample code.

import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.input.pointer.pointerInput

val layoutResult = remember { mutableStateOf<TextLayoutResult?>(null) }
val gesture = Modifier.pointerInput(onLongClick) {
    detectTapGestures(
        onLongPress = { pos ->
            layoutResult.value?.let { layout ->
                onLongClick(layout.getOffsetForPosition(pos))
            }
        }
    )
}

Text(
    text = text,
    modifier = modifier.then(gesture),
    style = style,
    softWrap = softWrap,
    overflow = overflow,
    maxLines = maxLines,
    onTextLayout = {
        onTextLayout(it)
        layoutResult.value = it
    }
)
Parameters
text: AnnotatedString

The text to be displayed.

onHover: (Int?) -> Unit

Callback that is executed when user hovers over the text with a mouse or trackpad. This callback is called with the hovered character's offset or null if the cursor is no longer hovering this.

modifier: Modifier = Modifier

Modifier to apply to this layout node.

style: TextStyle = TextStyle.Default

Style configuration for the text such as color, font, line height etc.

softWrap: Boolean = true

Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If softWrap is false, overflow and TextAlign may have unexpected effects.

overflow: TextOverflow = TextOverflow.Clip

How visual overflow should be handled.

maxLines: Int = Int.MAX_VALUE

An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow and softWrap. If it is not null, then it must be greater than zero.

onTextLayout: (TextLayoutResult) -> Unit = {}

Callback that is executed when a new text layout is calculated. A TextLayoutResult object that callback provides contains paragraph information, size of the text, baselines and other details. The callback can be used to add additional decoration or functionality to the text. For example, to draw selection around the text.

onClick: (Int) -> Unit

Callback that is executed when users click the text. This callback is called with clicked character's offset.

Note: API research for improvements on clickable text and related functionality is still ongoing so keeping this experimental to avoid future churn.

KeyboardActions

fun KeyboardActions(onAny: KeyboardActionScope.() -> Unit): KeyboardActions

Creates an instance of KeyboardActions that uses the specified lambda for all ImeActions.

Extension functions

appendInlineContent

fun AnnotatedString.Builder.appendInlineContent(
    id: String,
    alternateText: String = REPLACEMENT_CHAR
): Unit

Used to insert composables into the text layout. This method can be used together with the inlineContent parameter of BasicText. It will append the alternateText to this AnnotatedString and also mark this range of text to be replaced by a composable. BasicText will try to find an InlineTextContent in the map defined by inlineContent whose key equals to id, and it will use the InlineTextContent.children to replace this range of text.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.foundation.text.appendInlineContent
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.buildAnnotatedString

val myId = "inlineContent"
val text = buildAnnotatedString {
    append("Hello")
    // Append a placeholder string "[myBox]" and attach an annotation "inlineContent" on it.
    appendInlineContent(myId, "[myBox]")
}

val inlineContent = mapOf(
    Pair(
        // This tells the [BasicText] to replace the placeholder string "[myBox]" by
        // the composable given in the [InlineTextContent] object.
        myId,
        InlineTextContent(
            // Placeholder tells text layout the expected size and vertical alignment of
            // children composable.
            Placeholder(
                width = 0.5.em,
                height = 0.5.em,
                placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline
            )
        ) {
            // This [Box] will fill maximum size, which is specified by the [Placeholder]
            // above. Notice the width and height in [Placeholder] are specified in TextUnit,
            // and are converted into pixel by text layout.
            Box(modifier = Modifier.fillMaxSize().background(color = Color.Red))
        }
    )
)

BasicText(text = text, inlineContent = inlineContent)
Parameters
id: String

The id used to look up the InlineTextContent, it is referred by the inlineContent parameter of BasicText to replace the alternateText to the corresponding composable.

alternateText: String = REPLACEMENT_CHAR

The text to be replaced by the inline content. It's displayed when the inlineContent parameter of BasicText doesn't contain id. Accessibility features will also use this text to describe the inline content.

Throws
kotlin.IllegalArgumentException

if alternateText has zero length.

Top-level properties

LocalTextLinkStyle

@ExperimentalFoundationApi
val LocalTextLinkStyleProvidableCompositionLocal<SpanStyle>

Composition local used to change the style used by text links in the hierarchy.