androidandroid-textinputlayoutandroid-jetpack-composeandroid-compose-textfield

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


Solution

  • 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
                                        )
                                    )
                                }