jetpack compose 中带有提示文本的 TextField

问题描述 投票:0回答:9

我想用

textfield
中的
hint
文本创建
jetpackcompose
。有如何使用
textfield
创建
jectpack
的示例吗?谢谢

android android-textinputlayout android-jetpack-compose android-compose-textfield
9个回答
80
投票
compose_version = '1.0.0-beta07'

使用参数

placeholder
显示提示

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

使用参数

label
显示浮动标签

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

56
投票

你可以使用

  • label
    可组合项中的
    TextField
    参数可显示浮动标签
  • 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") 
    }
)


12
投票

您可以在

hintTextField
中创建
jetpackCompose
,如下代码:

@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
投票

Jetpack 撰写版本: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
投票
    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
投票

如果您想创建一个带有提示文本和自定义颜色的文本字段,这里是代码。

@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
投票

这对我有用(我认为它比 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
                            }
                        )
                    }
                }
            }
        }

    }
}

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
投票

从我发现的BasicTextField的示例中。如果文本字段为空,则 if 语句内的文本将显示为占位符文本。

{
    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,
        )
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.