Skip to main content

Customizing Border Style in Jetpack Compose TextField

Jetpack Compose, Google's modern UI toolkit for building Android applications, provides developers with a declarative approach to creating stunning user interfaces. Among its many components, the TextField stands out as a versatile widget for user input. While it works beautifully out of the box, there are instances where customizing its appearance, especially the border style, becomes essential for aligning with a specific app design or brand identity.

In this article, we delve deep into how you can customize the border style of a TextField in Jetpack Compose. We’ll explore advanced use cases, best practices, and how to achieve polished, professional results.

Default Border Style in Jetpack Compose

Before diving into customization, it’s essential to understand how the default TextField works. By default, Jetpack Compose offers two main types of text fields:

  1. OutlinedTextField: Comes with an outlined border.

  2. TextField: Provides a filled style without an explicit border.

Example:

import androidx.compose.material3.*
import androidx.compose.runtime.Composable

@Composable
fun DefaultTextFieldDemo() {
    Column {
        OutlinedTextField(
            value = "",
            onValueChange = {},
            label = { Text("Outlined TextField") }
        )

        TextField(
            value = "",
            onValueChange = {},
            label = { Text("Filled TextField") }
        )
    }
}

These components automatically adapt to Material Design specifications, ensuring consistency in appearance. However, customizing the border style often requires stepping beyond the default implementation.

Understanding the DecorationBox Parameter

Both OutlinedTextField and TextField rely on a TextFieldDefaults function to manage their styling. One powerful feature is the decorationBox parameter, which allows you to define custom decorations, including the border.

For instance, you can completely override the border rendering logic by leveraging decorationBox:

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

@Composable
fun CustomBorderTextField(value: String, onValueChange: (String) -> Unit) {
    BasicTextField(
        value = value,
        onValueChange = onValueChange,
        modifier = Modifier
            .border(2.dp, Color.Blue, RoundedCornerShape(8.dp))
            .padding(8.dp),
        decorationBox = { innerTextField ->
            Box(modifier = Modifier.padding(4.dp)) {
                innerTextField()
            }
        }
    )
}

Key Points:

  • The BasicTextField is used for lower-level control over the text field's behavior and styling.

  • The Modifier.border API allows you to define custom borders with shapes, widths, and colors.

Customizing Border Styles with Shapes and Colors

Jetpack Compose makes it straightforward to apply custom shapes and colors to borders using the Modifier API. Here's an example demonstrating a dynamic border color that changes based on focus state:

import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.graphics.Shape
import androidx.compose.foundation.focusable
import androidx.compose.foundation.interaction.*
import androidx.compose.runtime.remember
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.border

@Composable
fun DynamicBorderTextField(value: String, onValueChange: (String) -> Unit) {
    var isFocused by remember { mutableStateOf(false) }

    BasicTextField(
        value = value,
        onValueChange = onValueChange,
        modifier = Modifier
            .border(
                width = 2.dp,
                color = if (isFocused) Color.Green else Color.Gray,
                shape = RoundedCornerShape(12.dp)
            )
            .padding(8.dp)
            .focusable(interactionSource = MutableInteractionSource()) { isFocused = it },
        decorationBox = { innerTextField ->
            Box(modifier = Modifier.padding(4.dp)) {
                innerTextField()
            }
        }
    )
}

Advanced Customization: Gradient Borders

For more advanced designs, such as gradient borders, you can use the Brush API:

import androidx.compose.ui.graphics.Brush
import androidx.compose.foundation.border
import androidx.compose.ui.graphics.Color

@Composable
fun GradientBorderTextField(value: String, onValueChange: (String) -> Unit) {
    BasicTextField(
        value = value,
        onValueChange = onValueChange,
        modifier = Modifier
            .border(
                width = 3.dp,
                brush = Brush.horizontalGradient(
                    colors = listOf(Color.Red, Color.Blue)
                ),
                shape = RoundedCornerShape(8.dp)
            )
            .padding(8.dp),
        decorationBox = { innerTextField ->
            Box(modifier = Modifier.padding(4.dp)) {
                innerTextField()
            }
        }
    )
}

Best Practices for Custom Borders

When designing custom borders, consider the following best practices:

  1. Maintain Consistency: Ensure the custom styles align with your app’s design language.

  2. Handle Edge Cases: For example, consider different input states (focused, unfocused, error, disabled) and provide appropriate visual feedback.

  3. Reuse Styles: Use theming or create reusable composables to avoid code duplication.

  4. Optimize Performance: Avoid overly complex decorations that may impact rendering performance on lower-end devices.

Example: Unified Theme for Custom Text Fields

import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.graphics.Color
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.graphics.Brush

@Composable
fun ThemedTextField(value: String, onValueChange: (String) -> Unit, isError: Boolean = false) {
    val borderColor = if (isError) Color.Red else Color.Green
    val shape = CircleShape

    BasicTextField(
        value = value,
        onValueChange = onValueChange,
        modifier = Modifier
            .border(
                width = 2.dp,
                brush = Brush.linearGradient(
                    colors = listOf(borderColor, Color.Gray)
                ),
                shape = shape
            )
            .padding(8.dp),
        decorationBox = { innerTextField ->
            Box(modifier = Modifier.padding(4.dp)) {
                innerTextField()
            }
        }
    )
}

Conclusion

Customizing the border style of TextField in Jetpack Compose opens up endless possibilities for creating unique and engaging user interfaces. By leveraging the flexibility of Modifier, decorationBox, and the theming system, you can implement advanced designs tailored to your application's needs.

Jetpack Compose’s declarative approach ensures that even complex customizations remain maintainable and performant. Experiment with different border styles, shapes, and colors to create designs that stand out while delivering an exceptional user experience.

Recommended Next Steps:

  • Explore more about Modifier and its capabilities in Jetpack Compose.

  • Learn how to create custom themes to unify your app’s design language.

  • Experiment with advanced animations to make border transitions more engaging.

Popular posts from this blog

Restricting Jetpack Compose TextField to Numeric Input Only

Jetpack Compose has revolutionized Android development with its declarative approach, enabling developers to build modern, responsive UIs more efficiently. Among the many components provided by Compose, TextField is a critical building block for user input. However, ensuring that a TextField accepts only numeric input can pose challenges, especially when considering edge cases like empty fields, invalid characters, or localization nuances. In this blog post, we'll explore how to restrict a Jetpack Compose TextField to numeric input only, discussing both basic and advanced implementations. Why Restricting Input Matters Restricting user input to numeric values is a common requirement in apps dealing with forms, payment entries, age verifications, or any data where only numbers are valid. Properly validating input at the UI level enhances user experience, reduces backend validation overhead, and minimizes errors during data processing. Compose provides the flexibility to implement ...

jetpack compose - TextField remove underline

Compose TextField Remove Underline The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text. The following jetpack compose tutorial will demonstrate to us how we can remove (actually hide) the underline from a TextField widget in an android application. We have to apply a simple trick to remove (hide) the underline from the TextField. The TextField constructor’s ‘colors’ argument allows us to set or change colors for TextField’s various components such as text color, cursor color, label color, error color, background color, focused and unfocused indicator color, etc. Jetpack developers can pass a TextFieldDefaults.textFieldColors() function with arguments value for the TextField ‘colors’ argument. There are many arguments for this ‘TextFieldDefaults.textFieldColors()’function such as textColor, disabledTextColor, backgroundColor, cursorC...

jetpack compose - Image clickable

Compose Image Clickable The Image widget allows android developers to display an image object to the app user interface using the jetpack compose library. Android app developers can show image objects to the Image widget from various sources such as painter resources, vector resources, bitmap, etc. Image is a very essential component of the jetpack compose library. Android app developers can change many properties of an Image widget by its modifiers such as size, shape, etc. We also can specify the Image object scaling algorithm, content description, etc. But how can we set a click event to an Image widget in a jetpack compose application? There is no built-in property/parameter/argument to set up an onClick event directly to the Image widget. This android application development tutorial will demonstrate to us how we can add a click event to the Image widget and make it clickable. Click event of a widget allow app users to execute a task such as showing a toast message by cli...