affan ahmad
affan ahmad

Reputation: 1099

TextField with hint text in jetpack compose

I want to create textfield with hint text in jetpackcompose. Any example how create textfield using jectpack? Thanks

Upvotes: 57

Views: 66382

Answers (10)

J-iSkELo
J-iSkELo

Reputation: 103

@Composable
fun HintTextField(
    modifier: Modifier = Modifier,
    onValueChange: (String) -> Unit,
    value :String,
    hint :String,
) {
    var hasFocus by remember { mutableStateOf(false) }

    TextField(
        modifier = modifier.onFocusChanged { hasFocus = it.hasFocus },
        value = if (hasFocus || value.isNotEmpty()) value else hint,
        onValueChange = onValueChange
    )
}

Upvotes: 0

kometen
kometen

Reputation: 7842

From an example on BasicTextField I found. If the textfield is empty the text inside the if-statement is shown as a placeholder-text.

{
    BasicTextField(
        value = viewModel.name.value,
        onValueChange = { viewModel.name.value = it },
        textStyle = TextStyle(
            fontFamily = FontFamily.Serif
        ),
        singleLine = true
    )
    if (viewModel.name.value.isEmpty()) {
        Text(
            text = stringResource(id = R.string.name_english),
            color = Color.Gray,
            modifier = Modifier.padding(5.dp),
            fontFamily = FontFamily.Serif,
        )
    }
}

Upvotes: 0

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364868

You can use

  • the label parameter in the TextField composable to display a floating label
  • the placeholder parameter to display a placeholder when the text field is in focus and the input text is empty.

You can also use them together.

Something like:

var text by remember { mutableStateOf("text") }

OutlinedTextField(
        value = text, 
        onValueChange = {
             text = it
        },
        label = { 
           Text("Label") 
        }
)

enter image description here or

TextField(
    value = text, 
    onValueChange = {
         text = it
    },
    label = { 
         Text("Label") 
    },
    placeholder = { 
         Text("Placeholder") 
    }
)

enter image description here

Upvotes: 71

Parmesh
Parmesh

Reputation: 520

Hint Text Color

If you want to create a text field with hint text and custom color here is the code for that.

@Composable
fun PhoneOrEmail() {
     var text by remember { mutableStateOf("") }

     TextField(
         value = text,
         onValueChange = { text = it },
         label = { Text("Phone/email", style = TextStyle(color = 
         Color.Red)) }
    )//End of TextField
 }//End of Function

Upvotes: 2

Kashif Mehmood
Kashif Mehmood

Reputation: 11

    var textState by remember { mutableStateOf(TextFieldValue()) }
    var errorState by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf("") }


        TextField(
            value = textState,
            onValueChange = {
                textState = it
                when {
                    textState.text.isEmpty() -> {
                        errorState = true
                        errorMessage = "Please Enter Site Code"
                    }
                    else -> {
                        errorState = false
                        errorMessage = ""
                    }
                }
            },
            isError = errorState,
            label = {
                Text(
                    text = if (errorState) errorMessage
                    else "You Hint"
                )
            },
            modifier = Modifier
                .padding(top = 20.dp, start = 30.dp, end = 30.dp)
                .fillMaxWidth())

Upvotes: 1

Syed Hussain Mehdi
Syed Hussain Mehdi

Reputation: 1298

compose_version = '1.0.0-beta07'

Use parameter placeholder to show hint

TextField(value = "", onValueChange = {}, placeholder = { Text("Enter Email") })

Use parameter label to show floating label

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

Upvotes: 87

Dirk Hoffmann
Dirk Hoffmann

Reputation: 1573

the label parameter will be displayed as text if text is empty and moves above the textfield (as label) on typing input:

    @Composable
    fun SearchField() {
        val (text, setText) = remember { mutableStateOf(TextFieldValue("")) }
        Box(modifier = Modifier.width(180.dp).padding(2.dp)) {
            TextField(
                modifier = Modifier.fillMaxWidth(),
                value = text,
                onValueChange = { setText(it) },
                label = { Text("quick do:") },
            )
        }
    }

Upvotes: 0

Anas Mehar
Anas Mehar

Reputation: 2835

You can create hintTextField in jetpackCompose like below code:

@Composable
fun HintEditText(hintText: @Composable() () -> Unit) {
    val state = state { "" } // The unary plus is no longer needed. +state{""}
    val inputField = @Composable {
        TextField(
            value = state.value,
            onValueChange = { state.value = it }
        )
    }
    if (state.value.isNotEmpty()) {
        inputField()
    } else {
        Layout(inputField, hintText) { measurable, constraints ->
        val inputfieldPlacable = measurable[inputField].first().measure(constraints)
        val hintTextPlacable = measurable[hintText].first().measure(constraints)
        layout(inputfieldPlacable.width, inputfieldPlacable.height) {
                inputfieldPlacable.place(0.ipx, 0.ipx)
                hintTextPlacable.place(0.ipx, 0.ipx)
        } }
    }
}

Call @Compose function like below:

HintEditText @Composable {
                                Text(
                                    text = "Enter Email",
                                    style = TextStyle(
                                        color = Color.White,
                                        fontSize = 18.sp
                                    )
                                )
                            }

Upvotes: 13

Habib Kazemi
Habib Kazemi

Reputation: 2190

Jetpack compose version: dev08

The benefit of compose is that we can easily create our widgets by composing current composable functions.

We can just create a function with all parameters of the current TextField and add a hint: String parameter.

@Composable
fun TextFieldWithHint(
        value: String,
        modifier: Modifier = Modifier.None,
        hint: String,
        onValueChange: (String) -> Unit,
        textStyle: TextStyle = currentTextStyle(),
        keyboardType: KeyboardType = KeyboardType.Text,
        imeAction: ImeAction = ImeAction.Unspecified,
        onFocus: () -> Unit = {},
        onBlur: () -> Unit = {},
        focusIdentifier: String? = null,
        onImeActionPerformed: (ImeAction) -> Unit = {},
        visualTransformation: VisualTransformation? = null,
        onTextLayout: (TextLayoutResult) -> Unit = {}
) {
    Stack(Modifier.weight(1f)) {
        TextField(value = value,
                modifier = modifier,
                onValueChange = onValueChange,
                textStyle = textStyle,
                keyboardType = keyboardType,
                imeAction = imeAction,
                onFocus = onFocus,
                onBlur = onBlur,
                focusIdentifier = focusIdentifier,
                onImeActionPerformed = onImeActionPerformed,
                visualTransformation = visualTransformation,
                onTextLayout = onTextLayout)
        if (value.isEmpty()) Text(hint)
    }
}

We can use it like this:

@Model
object model { var text: String = "" }
TextFieldWithHint(value = model.text, onValueChange = { data -> model.text = data },
                    hint= "Type book name or author")

The pitfall of this approach is we are passing the hint as a string so if we want to style the hint we should add extra parameters to the TextFieldWithHint (e.g hintStyle, hintModifier, hintSoftWrap, ...)

The better approach is to accept a composable lambda instead of string:

@Composable
fun TextFieldWithHint(
        value: String,
        modifier: Modifier = Modifier.None,
        hint: @Composable() () -> Unit,
        onValueChange: (String) -> Unit,
        textStyle: TextStyle = currentTextStyle(),
        keyboardType: KeyboardType = KeyboardType.Text,
        imeAction: ImeAction = ImeAction.Unspecified,
        onFocus: () -> Unit = {},
        onBlur: () -> Unit = {},
        focusIdentifier: String? = null,
        onImeActionPerformed: (ImeAction) -> Unit = {},
        visualTransformation: VisualTransformation? = null,
        onTextLayout: (TextLayoutResult) -> Unit = {}
) {
    Stack(Modifier.weight(1f)) {
        TextField(value = value,
                modifier = modifier,
                onValueChange = onValueChange,
                textStyle = textStyle,
                keyboardType = keyboardType,
                imeAction = imeAction,
                onFocus = onFocus,
                onBlur = onBlur,
                focusIdentifier = focusIdentifier,
                onImeActionPerformed = onImeActionPerformed,
                visualTransformation = visualTransformation,
                onTextLayout = onTextLayout)
        if (value.isEmpty()) hint()
    }
}

We can use it like this:

@Model
object model { var text: String = "" }

TextFieldWithHint(value = model.text, onValueChange = { data -> model.text = data },
            hint= { Text("Type book name or author", style = TextStyle(color = Color(0xFFC7C7C7))) })

Upvotes: 2

Vladimir
Vladimir

Reputation: 2553

Here's what works for me (I think it's a bit simpler than what Anas posted since it's using the same component:

@Composable
fun TextBox(
    loginInput: LoginInput,
    hint: String = "enter value",
    color: Color = Color.LightGray,
    height: Dp = 50.dp
) {

    val state = +state { "" }
    state.value = if (loginInput.usernameEntered) loginInput.username else hint

    Surface(color = color) {
        Row {
            Container(modifier = Expanded, height = height) {
                Clip(shape = RoundedCornerShape(15.dp)) {
                    Padding(padding = 15.dp) {
                        TextField(
                            value = state.value,
                            keyboardType = KeyboardType.Text,
                            onFocus = {
                                if (!loginInput.usernameEntered)
                                    state.value = ""
                            },
                            onValueChange = {
                                loginInput.usernameEntered = true
                                loginInput.username = it
                                state.value = loginInput.username
                            }
                        )
                    }
                }
            }
        }

    }
}

Upvotes: 0

Related Questions