Jetpack compose 中带有提示文本的 TextField

Posted

技术标签:

【中文标题】Jetpack compose 中带有提示文本的 TextField【英文标题】:TextField with hint text in jetpack compose 【发布时间】:2020-03-11 23:20:20 【问题描述】:

我想在jetpackcompose 中创建带有hint 文本的textfield。任何示例如何使用jectpack 创建textfield?谢谢

【问题讨论】:

【参考方案1】:

使用1.0.0,您可以使用以下内容:

var text by remember  mutableStateOf("text") 

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

TextField(
    value = text, 
    onValueChange = 
         text = it
    ,
    label =  Text("Label") 
)

【讨论】:

注意:您需要这两个导入:import androidx.compose.runtime.getValueimport androidx.compose.runtime.setValue。 Android Studio 当前的金丝雀不会自动添加它们。 或者你可以像这样添加import androidx.compose.runtime.*【参考方案2】:
compose_version = '1.0.0-beta07'

使用参数placeholder显示提示

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

使用参数label显示浮动标签

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

【讨论】:

这是正确而优雅的答案。【参考方案3】:

您可以在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
                                    )
                                )
                            

【讨论】:

【参考方案4】:

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

【讨论】:

【参考方案5】:
    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())

【讨论】:

【参考方案6】:

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

    

【讨论】:

【参考方案7】:

如果文本为空,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:") ,
            )
        
    

【讨论】:

以上是关于Jetpack compose 中带有提示文本的 TextField的主要内容,如果未能解决你的问题,请参考以下文章

Jetpack Compose 文本超链接

如何在运行时添加 texdfields 并在 android jetpack compose 中管理这些文本字段值?

如何在 Jetpack Compose 中创建编辑器?

Jetpack Compose Text 超链接部分文本

Jetpack Compose - 居中文本

用于文本选择的浮动工具栏 Jetpack Compose