{% setvar book_path %}/reference/kotlin/androidx/_book.yaml{% endsetvar %} {% include "_shared/_reference-head-tags.html" %}

androidx.compose.foundation.text

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

InternalFoundationTextApi
Cmn

Top-level functions summary

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
@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 functions

BasicText

@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

BasicText

@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

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 = remember { MutableInteractionSource() },
    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 to control selection, cursor and text composition information. Please check TextFieldValue and corresponding BasicTextField overload for more information.

It is crucial that the value provided in the onValueChange is fed back into BasicTextField in order to have the final state of the text being displayed.

Example usage:

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") }
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
    }
)

Please keep in mind that onValueChange is useful to be informed about the latest state of the text input by users, however it is generally not recommended to modify the value that you get via onValueChange callback. Any change to this value may result in a context reset and end up with input session restart. Such a scenario would cause glitches in the UI or text input experience for users.

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.

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.Box
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.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MailOutline
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

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.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp

/** 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
)
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 = remember { MutableInteractionSource() }

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 in different Interactions.

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 = remember { MutableInteractionSource() },
    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 in the onValueChange is fed back into BasicTextField in order to have the final state of the text being displayed.

Example usage:

import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.Text
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
    }
)

Please keep in mind that onValueChange is useful to be informed about the latest state of the text input by users, however it is generally not recommended to modify the values in the TextFieldValue that you get via onValueChange callback. Any change to the values in TextFieldValue may result in a context reset and end up with input session restart. Such a scenario would cause glitches in the UI or text input experience for users.

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.

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.Box
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.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MailOutline
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

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()
        }
    }
)
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 = remember { MutableInteractionSource() }

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 in different Interactions.

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.

ClickableText

@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.material.Text
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.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.TextLayoutResult

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.

See also
BasicText
pointerInput
detectTapGestures

ClickableText

@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.material.Text
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.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.TextLayoutResult

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.

See also
BasicText
pointerInput
detectTapGestures

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.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.unit.em

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.

See also
InlineTextContent
BasicText