How to add Label to TextField in Android Jetpack Compose

By Mohammed Rashid •  September 1st, 2022 • 

TextField is a vital UI element for Android app development. Having a label on TextField helps users to identify input types. Here, let’s check how to add label to TextField in Android Jetpack Compose.

In the previous blog post about adding placeholder text to TextField we used the parameter placeholder. But here we have to use the label parameter. See the code snippet given below.

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

The text Username will be shown as a label. See the complete example 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("")}
        TextField(value = textInput, onValueChange = {textInput = it},
        label = { Text("Username")})
    }
    }


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

And following is the output.

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

Mohammed Rashid

Keep Reading