ant2009
ant2009

Reputation: 22616

placeholder text not shown until clicked in compose OutlinedTextField

I have the following composable OutlinedTextField

@Composable
fun EmailEntry(
    shouldShowLabel: Boolean = false,
    onEmailEntered: (emailText: String) -> Unit) {

    var emailText by rememberSaveable {
        mutableStateOf("")
    }

    OutlinedTextField(
        modifier = Modifier.fillMaxWidth(),
        singleLine = true,
        value = emailText,
        label = {
            if(shouldShowLabel) {
                Text(text = "Email")
            }
        },
        placeholder = {
            Text(text = "Email Address")
        },
        onValueChange = { newText ->
            emailText = newText
            onEmailEntered(emailText)
        },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)
    )
}

However, the placeholder text doesn't show until the user clicks in the textField. I want to placeholder to display, then disappear when the user starts typing.

enter image description here

Upvotes: 8

Views: 4349

Answers (2)

bmaum321
bmaum321

Reputation: 41

If you look into the code of the OutlinedTextField composable you can see the behavior of the label and the placeholder. If a label is provided, the placeholder alpha gets set to 0f when the field is not focused essentially hiding it. Here is a solution I used:

val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()
val label = when {
    isFocused -> whatever label you want
    !isFocused && data.value.isEmpty() -> whatever placeholder you want
    else -> fallback label
}

    OutlinedTextField(
    label = { Text(text = label) },
    interactionSource = interactionSource
    ...
)

Upvotes: 1

WS Ayan
WS Ayan

Reputation: 521

You can not use both label and placeholder for what you expecting. Rather use a Column to wrap and inside that use another Text above OutlinedTextField as label. Here is the example:

@Composable
fun EmailEntry() {
    var emailText by remember { mutableStateOf("") }
    Column() {
        Text(text = "Email")
        OutlinedTextField(
            modifier = Modifier.fillMaxWidth(),
            singleLine = true,
            value = emailText,
            placeholder = {
                Text(text = "Email Address")
            },
            onValueChange = { newText ->
                emailText = newText
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)
        )
    }

}

Upvotes: 6

Related Questions