Jetpack Compose 中带有提示文本的文本框

49

我想在jetpackcompose中创建带有hint文本的textfield。请问有没有使用jetpack创建textfield的示例?谢谢。

8个回答

79
compose_version = '1.0.0-beta07'

使用参数placeholder来显示提示信息

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

使用参数label来显示浮动标签。

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

1
它们不能一起使用。虽然它们应该能够一起工作,但却不能。您不能设置提示,而这个提示在字段被填充时变成标签。 - Brill Pappin
它们应该是互斥的吗?我在文档中没有看到这一点。 - Brill Pappin

55

您可以使用TextField组合中的label参数来显示浮动标签。

使用placeholder参数在文本字段聚焦且输入文本为空时显示占位符。

  • 您还可以一起使用它们。

就像这样:

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

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

在此输入图片描述 或者

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

这里输入图片描述


10
注意:你需要这两个导入项:import androidx.compose.runtime.getValueimport androidx.compose.runtime.setValue。目前的Android Studio预览版不会自动添加它们。 - Cristan
或者你可以像这样添加 import androidx.compose.runtime.* - Lee WonJoong

12

您可以使用以下代码在jetpackCompose中创建hintTextField

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

像下面这样调用@Compose函数:

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

1
    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())

1

Jetpack Compose 版本: dev08

Compose 的好处在于我们可以通过组合当前的可组合函数轻松创建小部件。

我们只需创建一个带有当前 TextField 的所有参数以及一个hint: String 参数的函数即可。

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

我们可以这样使用它:

我们可以这样使用它:

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

这种方法的缺陷在于我们将提示作为字符串传递,因此如果我们想要样式化提示,我们应该向 TextFieldWithHint 添加额外的参数(例如 hintStyle、hintModifier、hintSoftWrap 等)。
更好的方法是接受一个可组合的 lambda 表达式而不是字符串:
@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()
    }
}

我们可以像这样使用它:

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

1

Hint Text Color

如果你想创建一个带有提示文本和自定义颜色的文本字段,这是相应的代码。
@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

0

如果文本为空,则 label 参数将作为文本显示,并在输入时移动到文本字段上方(作为标签):

    @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:") },
            )
        }
    }

0

这是对我有效的方法(我认为它比Anas发布的方法简单一些,因为它使用了相同的组件):

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

    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接