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

BasicTextFieldKt

public final class BasicTextFieldKt


Summary

Public methods

static final void
@Composable
BasicTextField(
    @NonNull String value,
    @NonNull Function1<@NonNull StringUnit> onValueChange,
    @NonNull Modifier modifier,
    boolean enabled,
    boolean readOnly,
    @NonNull TextStyle textStyle,
    @NonNull KeyboardOptions keyboardOptions,
    @NonNull KeyboardActions keyboardActions,
    boolean singleLine,
    int maxLines,
    int minLines,
    @NonNull VisualTransformation visualTransformation,
    @NonNull Function1<@NonNull TextLayoutResultUnit> onTextLayout,
    @NonNull MutableInteractionSource interactionSource,
    @NonNull Brush cursorBrush,
    @Composable @NonNull Function1<@Composable @NonNull Function0<Unit>, Unit> decorationBox
)

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

static final void
@Composable
BasicTextField(
    @NonNull TextFieldValue value,
    @NonNull Function1<@NonNull TextFieldValueUnit> onValueChange,
    @NonNull Modifier modifier,
    boolean enabled,
    boolean readOnly,
    @NonNull TextStyle textStyle,
    @NonNull KeyboardOptions keyboardOptions,
    @NonNull KeyboardActions keyboardActions,
    boolean singleLine,
    int maxLines,
    int minLines,
    @NonNull VisualTransformation visualTransformation,
    @NonNull Function1<@NonNull TextLayoutResultUnit> onTextLayout,
    @NonNull MutableInteractionSource interactionSource,
    @NonNull Brush cursorBrush,
    @Composable @NonNull Function1<@Composable @NonNull Function0<Unit>, Unit> decorationBox
)

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

Public methods

BasicTextField

@Composable
public static final void BasicTextField(
    @NonNull String value,
    @NonNull Function1<@NonNull StringUnit> onValueChange,
    @NonNull Modifier modifier,
    boolean enabled,
    boolean readOnly,
    @NonNull TextStyle textStyle,
    @NonNull KeyboardOptions keyboardOptions,
    @NonNull KeyboardActions keyboardActions,
    boolean singleLine,
    int maxLines,
    int minLines,
    @NonNull VisualTransformation visualTransformation,
    @NonNull Function1<@NonNull TextLayoutResultUnit> onTextLayout,
    @NonNull MutableInteractionSource interactionSource,
    @NonNull Brush cursorBrush,
    @Composable @NonNull Function1<@Composable @NonNull Function0<Unit>, Unit> decorationBox
)

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
@NonNull String value

the input String text to be shown in the text field

@NonNull Function1<@NonNull StringUnit> onValueChange

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

@NonNull Modifier modifier

optional Modifier for this text field.

boolean enabled

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

boolean readOnly

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

@NonNull TextStyle textStyle

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

@NonNull KeyboardOptions keyboardOptions

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

@NonNull KeyboardActions keyboardActions

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.

boolean singleLine

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.

int maxLines

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.

int minLines

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.

@NonNull VisualTransformation visualTransformation

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

@NonNull Function1<@NonNull TextLayoutResultUnit> onTextLayout

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.

@NonNull MutableInteractionSource interactionSource

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.

@NonNull Brush cursorBrush

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

@Composable @NonNull Function1<@Composable @NonNull Function0<Unit>, Unit> decorationBox

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
public static final void BasicTextField(
    @NonNull TextFieldValue value,
    @NonNull Function1<@NonNull TextFieldValueUnit> onValueChange,
    @NonNull Modifier modifier,
    boolean enabled,
    boolean readOnly,
    @NonNull TextStyle textStyle,
    @NonNull KeyboardOptions keyboardOptions,
    @NonNull KeyboardActions keyboardActions,
    boolean singleLine,
    int maxLines,
    int minLines,
    @NonNull VisualTransformation visualTransformation,
    @NonNull Function1<@NonNull TextLayoutResultUnit> onTextLayout,
    @NonNull MutableInteractionSource interactionSource,
    @NonNull Brush cursorBrush,
    @Composable @NonNull Function1<@Composable @NonNull Function0<Unit>, Unit> decorationBox
)

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
@NonNull TextFieldValue value

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

@NonNull Function1<@NonNull TextFieldValueUnit> onValueChange

Called when the input service updates the values in TextFieldValue.

@NonNull Modifier modifier

optional Modifier for this text field.

boolean enabled

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

boolean readOnly

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

@NonNull TextStyle textStyle

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

@NonNull KeyboardOptions keyboardOptions

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

@NonNull KeyboardActions keyboardActions

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.

boolean singleLine

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.

int maxLines

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.

int minLines

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.

@NonNull VisualTransformation visualTransformation

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

@NonNull Function1<@NonNull TextLayoutResultUnit> onTextLayout

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.

@NonNull MutableInteractionSource interactionSource

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.

@NonNull Brush cursorBrush

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

@Composable @NonNull Function1<@Composable @NonNull Function0<Unit>, Unit> decorationBox

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.