How to add Border to TextField in Android Jetpack Compose

By Mohammed Rashid •  September 1st, 2022 • 

TextField is one of the most important UI components. Adding a border to TextField makes the UI more beautiful. Let’s learn how to add a border to TextField in Android Jetpack Compose.

Usually, we prefer TextField composable to add text inputs. In this case, you should use OutlinedTextField composable. See the code snippet given below.

var textInput by remember { mutableStateOf("")}
OutlinedTextField(value = textInput, onValueChange = {textInput = it},
label = { Text("Username")})

The complete example is given below.

package com.example.example

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.example.ui.theme.ExampleTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    TextfieldExample()
                }
            }
        }
    }
}

@Composable
fun TextfieldExample() {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        var textInput by remember { mutableStateOf("")}
        OutlinedTextField(value = textInput, onValueChange = {textInput = it},
        label = { Text("Username")})
    }
    }


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    ExampleTheme {
        TextfieldExample()
    }
}

Following is the output.

That’s how you add border to TextField in Jetpack Compose.

Mohammed Rashid

Keep Reading