Jetpack Compose: How to use OutlinedTextField

Introduction

In the world of Android development, Jetpack Compose has revolutionized how developers create user interfaces. This modern toolkit simplifies the process of building native Android applications with minimal boilerplate code, enabling developers to focus on what really matters: delivering a polished user experience. By embracing a declarative programming approach, Jetpack Compose allows you to describe how your UI should look and behave, significantly reducing the need for complex XML layouts.

One of the most commonly used UI components in applications is the text field. Whether for capturing user inputs, such as names, addresses, or search queries, a well-designed text field can greatly enhance user interaction. In this guide, we’ll break down a simple example of how to create and customize an OutlinedTextField using Jetpack Compose in Kotlin. The example demonstrates how to capture user input and display it dynamically on the screen, making it a perfect introduction for those getting started with Jetpack Compose.

Setting Up the Main Activity

The core of our example lies in the MainActivity, where we set up the content of our application using the setContent function. This function is unique to Jetpack Compose and replaces the traditional setContentView method used in XML-based layouts. By utilizing setContent, we declare our UI components within Kotlin code, making the entire UI structure more intuitive and flexible.

Within the setContent block, the MainContent() composable function is invoked to define the layout. The composable paradigm of Jetpack Compose allows functions like MainContent to be annotated with @Composable, indicating that they are responsible for rendering the UI. This makes the code modular and reusable, as components can be combined or nested with ease.

Creating the User Input Field

The heart of this example is the OutlinedTextField, a versatile input component provided by Jetpack Compose. In this example, we utilize the OutlinedTextField to create a text input box with a visible border and a label prompting the user to enter the name of a city. This text field accepts user input dynamically, making it ideal for scenarios where user interaction is required.

To manage the state of the input field, the code uses the remember function combined with mutableStateOf. This ensures that the text entered by the user is stored and tracked within the component's state. Every time the user types or deletes a character, the onValueChange callback is triggered, updating the state with the new text. By leveraging the power of state management in Jetpack Compose, we can seamlessly update the UI without any manual refreshes.

Styling the Text Field

Jetpack Compose offers extensive customization options, allowing you to adjust the appearance of UI elements easily. In the OutlinedTextField, we apply a custom TextStyle to control the color, font size, and weight of the input text. For this example, we set the text color to black and the font size to 22sp, making the input both readable and visually appealing. The bold font weight further emphasizes the text, creating a clear distinction between the label and the user's input.

The label for the text field, "City Name?", is defined within the label parameter. Labels are crucial in guiding users on what information is expected, thus enhancing the overall user experience. Additionally, the padding applied to the column containing the text field ensures that the UI elements are spaced out nicely, providing a clean and organized layout.

Displaying the User Input

Once the user enters a city name in the text field, it is immediately reflected below the input box. This is achieved by adding a Text composable that reads the current value of the textState. The text content displayed is prefixed with "Your city is:", followed by the user's input. This dynamic binding between the text field and the displayed text showcases the real-time reactivity that Jetpack Compose excels at.

To enhance the appearance of the output text, additional styling is applied. We set the font size to 22sp, use a sans-serif font family, and style the text in italics. The blue color chosen for the output text creates a visual distinction from the input field, making the displayed information stand out. The extra padding ensures there is adequate space between the input field and the displayed text, contributing to a user-friendly interface.

Previewing the UI

One of the standout features of Jetpack Compose is its built-in support for previews. By using the @Preview annotation, you can visualize your UI components directly within the Android Studio editor, without needing to run the app on an actual device. In our example, a ComposablePreview function is provided, allowing you to see how the MainContent composable renders. This feature accelerates the development process, enabling rapid iteration and testing of UI designs.

Summary

This example highlights how Jetpack Compose simplifies Android UI development by eliminating the need for XML layouts and providing a fully declarative approach. By creating an OutlinedTextField with state management, we demonstrated how to capture user input dynamically and display it in real time. The flexibility in styling ensures that developers can easily customize the appearance of their components, resulting in a polished and user-friendly interface.

As Jetpack Compose continues to evolve, mastering its components and techniques will open new possibilities for creating modern Android applications. This example serves as a foundational step, showcasing how even basic components like text fields can be implemented efficiently using this powerful toolkit.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        Column(Modifier.padding(25.dp)) {
            val textState = remember{ mutableStateOf(TextFieldValue()) }

            OutlinedTextField(
                value = textState.value,
                onValueChange = { textState.value = it },
                label = { Text("City Name?") },
                textStyle = TextStyle(
                    color = Color.Black,
                    fontSize = 22.sp,
                    fontWeight = FontWeight.Bold
                )
            )

            Text(
                text = "Your city is : " + textState.value.text,
                fontSize = 22.sp,
                color = Color.Blue,
                fontFamily = FontFamily.SansSerif,
                fontStyle = FontStyle.Italic,
                modifier = Modifier.padding(top = 25.dp)
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials