Android Jetpack

Getting Started with Jetpack Compose Textfield

Pinterest LinkedIn Tumblr

Are you new to Jetpack Compose Textfield? In this tutorial, we’re going to talk about Jetpack Compose Textfield. This post will help you get started with the basics of creating and customizing text fields using Jetpack Compose. Learn how to create text fields, add input validation, and more with this comprehensive guide.

What is Jetpack Compose Textfield?

The Jetpack Compose Text field is also very important, right? TextField is composable which will allow us to get some user input and we want to have this interaction with our users.

So we need to be able to get some information. It allows developers to easily create and customize text fields with features like input validation, hint text, and more. So let’s go ahead and try it out.

The following option TextField is Provided

@Composable
fun TextField(
    value: TextFieldValue,
    onValueChange: (TextFieldValue) -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    textStyle: TextStyle = LocalTextStyle.current,
    label: @Composable (() -> Unit)? = null,
    placeholder: @Composable (() -> Unit)? = null,
    leadingIcon: @Composable (() -> Unit)? = null,
    trailingIcon: @Composable (() -> Unit)? = null,
    isError: Boolean = false,
    visualTransformation: VisualTransformation = VisualTransformation.None,
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
    keyboardActions: KeyboardActions = KeyboardActions(),
    singleLine: Boolean = false,
    maxLines: Int = Int.MAX_VALUE,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    shape: Shape =
        MaterialTheme.shapes.small.copy(bottomEnd = ZeroCornerSize, bottomStart = ZeroCornerSize),
    colors: TextFieldColors = TextFieldDefaults.textFieldColors()
)

Creating a basic Text Field in Compose.

I’m going to add a Jetpack Compose TextField here. Jetpack Compose is relying on state to kind of update the information in a composable for TextField since we require user input and require some state information for holding the input. Now for TextField, we have a lot of customization that we can do, we did it for simple text, color, size, weight and so on. The important this is

    val name = remember { mutableStateOf(TextFieldValue("")) }
    TextField(
      modifier = Modifier.fillMaxWidth(),
      value = name.value,
      onValueChange = { name.value = it },
      label = { Text(text = "First Name") },
      placeholder = { Text(text = "Surya") },
      keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)
    )

But I want to talk about two things the label and the placeholder. The label will kind of tell the user what this text field is for, and the placeholder will provide some default value for that user.

OutlinedTextField

    val surname = remember { mutableStateOf(TextFieldValue("")) }
    OutlinedTextField(
      modifier = Modifier.fillMaxWidth(),
      label = { Text(text = "Last Name") },
      placeholder = { Text(text = "Kushwaha") },
      value = surname.value,
      onValueChange = { surname.value = it })
  }

Customizing your text field.

Jetpack Compose TextField is the ability to customize the appearance and behavior of your TextField You can use various parameters and modifiers to change things like the text color, background color, border style, and more.

    • enabled – controls the enabled state of the TextField
    • readOnly – controls the editable state of the TextField. When true, the text field can not be modified
    • textStyle – the style to be applied to the input text.
    • leadingIcon – icon to be displayed at the beginning of the text field container
    • trailingIcon – con to be displayed at the end of the text field container
    • isError – indicates if the text field’s current value is in error state.
    • keyboardOptions – software keyboard options that contain configuration such as KeyboardType and ImeAction.
    • singleLine – when set to true, this text field becomes a single horizontally scrolling text field
    • maxLines – the maximum height in terms of a maximum number of visible lines
    • colors – TextFieldColors that will be used to resolve color of the text, content (including label, placeholder, leading and trailing icons, indicator line) and background for this text field in different states.

    Find a suitable example for you

    I have created followings example, I tried to cover all use cases, Please choose best on need

    Normal TextField Example

        val name = remember { mutableStateOf(TextFieldValue("")) }
        TextField(
          modifier = Modifier.fillMaxWidth(),
          value = name.value,
          onValueChange = { name.value = it },
          label = { Text(text = "First Name") },
          placeholder = { Text(text = "Surya") },
          keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)
        )
    

    OutlinedTextField Example

        val surname = remember { mutableStateOf(TextFieldValue("")) }
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
          label = { Text(text = "Last Name") },
          placeholder = { Text(text = "Kushwaha") },
          value = surname.value,
          onValueChange = { surname.value = it })

    TextField leadingIcon Example

        val lastName = remember { mutableStateOf(TextFieldValue("")) }
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
          label = { Text(text = "Last Name") },
          placeholder = { Text(text = "Kushwaha") },
          leadingIcon = {
            Icon(
              painter = painterResource(id = R.drawable.ic_person),
              contentDescription = null,
              tint = Color.Blue
            )
          },
          value = lastName.value,
          onValueChange = { lastName.value = it })

    TextField with trailingIcon Example

        val email = remember { mutableStateOf(TextFieldValue("")) }
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
          label = { Text(text = "Email") },
          placeholder = { Text(text = "Enter email") },
          trailingIcon = {
            Icon(
              painter = painterResource(id = R.drawable.ic_email),
              contentDescription = null,
              tint = Color.Blue
            )
          },
          value = email.value,
          onValueChange = { email.value = it })

    Handling user input and validation.

    Once you have created your Jetpack Compose Textfield, you will need to handle user input and validation. This involves checking that the user has entered valid data into the text field, such as a valid email address or password. You can use the onValueChange parameter to listen for changes to the text field and validate the input as the user types. You can also use the isError parameter to display an error message if the user enters invalid data. By properly handling user input and validation, you can ensure that your app is secure and user-friendly.

        var emailErrMsg = remember { mutableStateOf("") }
        var isEmailValid = remember { mutableStateOf(false) }
        val email2 = remember { mutableStateOf(TextFieldValue("")) }
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
          label = { Text(text = "Email") },
          placeholder = { Text(text = "Enter email") },
          leadingIcon = {
            Icon(
              painter = painterResource(id = R.drawable.ic_email),
              contentDescription = null,
              tint = Color.Blue
            )
          },
          isError = isEmailValid.value,
          value = email2.value,
          onValueChange = {
            email2.value = it
            // write logic validation logic here or call ViewModal function
            if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email2.value.text).matches()) {
              isEmailValid.value = true
              emailErrMsg.value = "Input proper email id"
            } else {
              emailErrMsg.value = ""
              isEmailValid.value = false 
            }
          })
        Text(
          modifier = Modifier.fillMaxWidth(),
          text = emailErrMsg.value,
          fontSize = 14.sp,
          color = Color.Red
        )

    Conclusion

    Jetpack Compose Textfield is a powerful tool for creating text fields in your Android app. I hope this post will help you a lot. If you have any quires please follow us on social media.

    Write A Comment