How to add Hint Text to TextField in Android Jetpack Compose

By Mohammed Rashid •  September 1st, 2022 • 

A placeholder or hint text helps users to get enough idea about what to enter in a TextField. In this tutorial, let’s learn how to add hint text or placeholder to TextField in Android Jetpack Compose.

I already have a blog post on how to add TextField where I used TextField composable. The TextField has a parameter named Placeholder which helps us to add hint text. See the code snippet given below.

var textInput by remember { mutableStateOf("")}
TextField(value = textInput, onValueChange = {textInput = it},
        placeholder = { Text("Enter here")})

Here, Enter here is the placeholder text. See the complete code 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},
        placeholder = { Text("Enter here")})
    }

    }


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

The output of the above Jetpack Compose example is as given below.

That’s how you hint text to TextField in Jetpack Compose.

Mohammed Rashid

Keep Reading