Text Field in Jetpack Compose

Text fields play a crucial role in user interaction, allowing users to input and edit text within an application. With Jetpack Compose, the modern UI toolkit for Android development, creating dynamic and user-friendly text fields has never been easier. In this comprehensive guide, we will explore the powerful features of the text field in Jetpack Compose, providing detailed explanations and example programs to showcase their various options and capabilities.

The Basics of Text Field in Compose:

In Jetpack Compose, text fields are represented by the TextField composable. They offer a wide range of properties and options to customize their behaviour and appearance. Let’s dive into the essential options provided by the TextField composable.

  1. Value and OnValueChange: The value parameter represents the current text value of the text field. It can be bound to a mutable state variable and updated using the onValueChange callback. The value is usually stored in a mutable state variable, allowing it to be updated and synchronized with the text field’s content. Here’s an example program:
var textFieldText by remember { mutableStateOf("") }

TextField(
    value = textFieldText,
    onValueChange = { newText ->
        textFieldText = newText
    }
)

In this example, textFieldText is a mutable state variable holding the current text value. The onValueChange callback is triggered whenever the user modifies the text field, allowing you to perform actions or update other UI components based on the new text.

  1. KeyboardOptions and KeyboardType: The keyboardOptions parameter allows you to specify the behaviour of the keyboard associated with the text field. By using the keyboardType option, you can define the type of keyboard that appears when the field gains focus. This feature is particularly useful for input fields that require specific types of text, such as emails, phone numbers, or numbers. Here’s an example of using the keyboardOptions parameter.
TextField(
    value = textFieldText,
    onValueChange = { textFieldText = it },
    keyboardOptions = KeyboardOptions(
        keyboardType = KeyboardType.Email,
        imeAction = ImeAction.Done
    )
)

In this example, the keyboardType is set to KeyboardType.Email, which displays an email-specific keyboard. Additionally, the imeAction specifies the action to be taken when the user interacts with the IME (Input Method Editor) button, in this case, “Done.”

  1. Visual Transformation: The visualTransformation parameter allows you to transform the visual representation of the text as it is displayed in the text field. For instance, you can mask passwords or format text in a specific way. This feature is valuable when handling sensitive information or when you want to enforce a particular text format. Here’s an example of password masking:
TextField(
    value = textFieldText,
    onValueChange = { textFieldText = it },
    visualTransformation = PasswordVisualTransformation()
)

In this example, the PasswordVisualTransformation() masks the entered characters as bullets to enhance security for password input.

  1. Modifier and Styling: Compose provides the modifier parameter to apply various modifiers to the text field, enabling customization and styling options. For example, you can add padding, adjust size, or define custom styles using the Modifier API. This feature allows you to align the text field with the overall design of your application. Here’s an example of applying a modifier:
TextField(
    value = textFieldText,
    onValueChange = { textFieldText = it },
    modifier = Modifier
        .padding(16.dp)
        .fillMaxWidth()
        .height(48.dp)
)
  1. Decoration and Visual Customization: Compose allows you to enhance the visual appearance of text fields by applying decorations and customizing their style. The TextField composable provides the decorations parameter, which enables you to add visual elements such as icons, borders, or background colours. Here’s an example:
TextField(
    value = textFieldText,
    onValueChange = { textFieldText = it },
    modifier = Modifier
        .fillMaxWidth()
        .height(56.dp),
    textStyle = TextStyle(color = Color.Black),
    shape = RoundedCornerShape(8.dp),
    colors = TextFieldDefaults.textFieldColors(
        backgroundColor = Color.LightGray,
        cursorColor = Color.Blue,
        focusedIndicatorColor = Color.Green,
        unfocusedIndicatorColor = Color.Red
    ),
    leadingIcon = { Icon(Icons.Default.Person, contentDescription = "User Icon") },
    trailingIcon = { Icon(Icons.Default.Clear, contentDescription = "Clear Icon") },
    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)
)

In this example, we have added various customizations to the text field. The textStyle property sets the text colour to black. The shape parameter applies rounded corners to the text field. The colours parameter allows customization of the background colour, cursor colour, and indicator colours. The leadingIcon and trailingIcon parameters add icons to the left and right sides of the text field, respectively.

  1. Error Handling and Validation: Text fields often require input validation and error handling to provide a seamless user experience. Compose offers mechanisms to validate user input and display error messages when needed. Here’s an example that demonstrates error handling:
var textFieldText by remember { mutableStateOf("") }
var isError by remember { mutableStateOf(false) }
val errorText = "Please enter a valid email"

TextField(
    value = textFieldText,
    onValueChange = { newText ->
        textFieldText = newText
        isError = !isValidEmail(newText) // Custom validation function
    },
    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
    isError = isError,
    singleLine = true,
    label = { Text(text = "Email") },
    colors = TextFieldDefaults.textFieldColors(
        backgroundColor = Color.White,
        cursorColor = Color.Blue,
        focusedIndicatorColor = Color.Green,
        unfocusedIndicatorColor = Color.Red,
        errorIndicatorColor = Color.Red
    ),
    modifier = Modifier.fillMaxWidth()
)

if (isError) {
    Text(text = errorText, color = Color.Red)
}

In this example, the isError variable is used to track whether the input is valid or not. The isError parameter of the TextField composable is set accordingly, and the errorIndicatorColor property customizes the colour of the error indicator. Additionally, an error message is displayed below the text field when isError is true.

  1. Input Filters and ImeAction: Compose provides input filters and customization of the IME action to control the allowed input and user interaction. Here’s an example:
val passwordRegex = Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$")

TextField(
    value = textFieldText,
    onValueChange = { newText ->
        textFieldText = newText
    },
    keyboardOptions = KeyboardOptions(
        keyboardType = KeyboardType.Password,
        imeAction = ImeAction.Done
    ),
    visualTransformation = PasswordVisualTransformation(),
    singleLine = true,
    label = { Text(text = "Password") },
    colors = TextFieldDefaults.textFieldColors(
        backgroundColor = Color.White,
        cursorColor = Color.Blue,
        focusedIndicatorColor = Color.Green,
        unfocusedIndicatorColor = Color.Red
    ),
    modifier = Modifier.fillMaxWidth(),
    visualTransformationFilter = { passwordRegex.containsMatchIn(it) }
)

In this example, the keyboardOptions specify a password keyboard and set the IME action to “Done”. The visualTransformation applies password masking. The visualTransformationFilter uses a regular expression to validate the input and allows only strong passwords.

Conclusion:

Jetpack Compose’s TextField composable provides a comprehensive set of options and features to create flexible and interactive text fields in Android applications. By leveraging these options, you can enhance user experience, handle input validation, customize visual appearance, and control user interactions. Experiment with different combinations and explore the possibilities to create text fields tailored to your specific application requirements.

Spread the love
Scroll to Top
×