问题描述
当我将 TextField 的高度设置为 40dp 时,我无法像这张图片一样正确地看到文本。
我该如何解决这个问题?
@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 中有一个嵌入的高度。由于您固定了高度,因此内容未完全显示。解决问题的方法共有三种:您可以选择解决问题所需的方法。
-
显然需要增加
TextField
中Compose
的高度。TextField
的最小高度在TextFieldDefaults
中定义。minHeight
的TextField
为 56dp。你的 modifier.height 只需要高于这个高度。而TextFiled内置的padding为16dp -
减小字体的 fontSize 以适应减小的高度。
-
自定义文本字段。如果您觉得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)
)
}