gpt4 book ai didi

android - TextField 中的文本问题 - Android Jetpack Compose

转载 作者:行者123 更新时间:2023-12-05 03:40:01 25 4
gpt4 key购买 nike

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

我该如何解决这个问题?

an image of a search bar where the text is clipped and not clearly visible

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

最佳答案

Compose 的 TextField 中有一个嵌入高度。由于固定了高度,内容显示不完整。解决问题的方法有三种:你可以选择你需要的一种来解决问题。

  1. 显然,您需要在 Compose 中增加 TextField 的高度。 TextField 的最小高度在 TextFieldDefaults 中定义。 TextFieldminHeight 为 56dp。您的 modifier.height 只需高于此高度即可。而TextFiled内置的padding是16dp

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

  3. 自定义 TextField。如果你觉得TextField不合适,你可以自定义TextField来满足你的需求。使用BasicTextField定义一个符合要求的输入框。我把我自己的 BasicTextField 放在这里。大家可以先试试,写成对应的reproduce:

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

关于android - TextField 中的文本问题 - Android Jetpack Compose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68330300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com