微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

TextField 中的文本问题 - Android Jetpack Compose

如何解决TextField 中的文本问题 - Android Jetpack Compose

当我将 TextField 的高度设置为 40dp 时,我无法像这张图片一样正确地看到文本。

我该如何解决这个问题?

preview image

@Composable
fun SearchTextField(
    onSearchClick: () -> Unit
) {
    var text by remember { mutableStateOf("") }

    TextField(
        value = text,onValueChange = { text = it },placeholder = { Text("Search") },singleLine = true,leadingIcon = {
            Icon(
                imageVector = Icons.Filled.Search,contentDescription = ""
            )
        },modifier = Modifier.height(40.dp),shape = RoundedCornerShape(10.dp),colors = TextFieldDefaults.textFieldColors(
            focusedindicatorColor = Color.Transparent,unfocusedindicatorColor = Color.Transparent
        ),keyboardActions = KeyboardActions {
            onSearchClick()
        },textStyle = TextStyle.Default
    )
}

解决方法

文本大小太大,无法容纳 40 DP。这很明显。

,

在 Compose 的 TextField 中有一个嵌入的高度。由于您固定了高度,因此内容未完全显示。解决问题的方法共有三种:您可以选择解决问题所需的方法。

  1. 显然需要增加TextFieldCompose的高度。 TextField 的最小高度在 TextFieldDefaults 中定义。 minHeightTextField 为 56dp。你的 modifier.height 只需要高于这个高度。而TextFiled内置的padding为16dp

  2. 减小字体的 fontSize 以适应减小的高度。

  3. 自定义文本字段。如果您觉得TextField 不适合,您可以自定义TextField 以满足您的需求。使用 BasicTextField 定义符合要求的输入框。我把我自己的 BasicTextField 放在这里。可以先试试,写成对应的repeat:

@Composable
fun InputEditText(
    value: String,modifier: Modifier,onValueChange: (String) -> Unit,contentTextStyle: TextStyle,hintTextStyle: TextStyle,placeHolderString: String = "",enabled: Boolean = true,readOnly: Boolean = false,singleLine: Boolean = false,maxLines: Int = Int.MAX_VALUE,keyboardOptions: KeyboardOptions = KeyboardOptions.Default,keyboardActions: KeyboardActions = KeyboardActions.Default,cursorColor: Color = Color.Black,) {
    BasicTextField(
        value = value,onValueChange = onValueChange,modifier = modifier,textStyle = contentTextStyle,decorationBox = {innerTextField ->
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .offset {
                        if (contentTextStyle.textAlign == TextAlign.Start)
                            IntOffset(x = 10,y = 0)
                        else
                            IntOffset(x = 0,y = 0)
                    },contentAlignment = Alignment.CenterStart,) {
                if (value.isEmpty()) {
                    Text(
                        text = placeHolderString,color = hintTextStyle.color,fontSize = hintTextStyle.fontSize
                    )
                }

                innerTextField()

            }
        },enabled = enabled,readOnly = readOnly,singleLine = singleLine,maxLines = maxLines,keyboardOptions = keyboardOptions,keyboardActions = keyboardActions,cursorBrush = SolidColor(cursorColor)
    )
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。