这个功能有一个功能请求,我建议你给它加星,也许可以评论它,因为它已经有一段时间没有更新了。
在此之前,您可以使用此 hack。我用额外的行渲染一个不可见的文本字段,使其占据正确的大小,然后将该大小应用于真实的文本字段。我也通过modifier
andtextStyle
作为 for 的键,remember
这样heightUpdateNeeded
如果你改变它们,高度将被重新计算。如果您传递的任何其他参数可能会改变视图的大小,您也应该将它们传递给记住。
@Composable
fun MinLinesOutlinedTextField(
value: String,
onValueChange: (String) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
readOnly: Boolean = false,
textStyle: TextStyle = LocalTextStyle.current,
label: @Composable (() -> Unit)? = null,
placeholder: @Composable (() -> Unit)? = null,
leadingIcon: @Composable (() -> Unit)? = null,
trailingIcon: @Composable (() -> Unit)? = null,
isError: Boolean = false,
visualTransformation: VisualTransformation = VisualTransformation.None,
keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
keyboardActions: KeyboardActions = KeyboardActions.Default,
singleLine: Boolean = false,
minLines: Int,
maxLines: Int = Int.MAX_VALUE,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
shape: Shape = MaterialTheme.shapes.small,
colors: TextFieldColors = TextFieldDefaults.outlinedTextFieldColors()
) {
val heightState = remember { mutableStateOf<Int?>(null) }
var heightUpdateNeeded by remember(modifier, textStyle) { mutableStateOf(true) }
val height = with(LocalDensity.current) {
heightState.value?.toDp()
} // to use if nullable unwrapping
Box(modifier.height(IntrinsicSize.Min).width(IntrinsicSize.Min)) {
if (heightUpdateNeeded) {
OutlinedTextField(
value = value + "\n".repeat(minLines),
onValueChange = onValueChange,
enabled = enabled,
readOnly = readOnly,
textStyle = textStyle,
label = label,
placeholder = placeholder,
leadingIcon = leadingIcon,
trailingIcon = trailingIcon,
isError = isError,
visualTransformation = visualTransformation,
keyboardOptions = keyboardOptions,
keyboardActions = keyboardActions,
singleLine = singleLine,
maxLines = maxLines,
interactionSource = interactionSource,
shape = shape,
colors = colors,
modifier = Modifier
.fillMaxSize()
.alpha(0f)
.onSizeChanged {
heightUpdateNeeded = false
println("onSizeChanged $it")
heightState.value = it.height
}
)
}
if (height != null) {
OutlinedTextField(
value = value,
onValueChange = onValueChange,
enabled = enabled,
readOnly = readOnly,
textStyle = textStyle,
label = label,
placeholder = placeholder,
leadingIcon = leadingIcon,
trailingIcon = trailingIcon,
isError = isError,
visualTransformation = visualTransformation,
keyboardOptions = keyboardOptions,
keyboardActions = keyboardActions,
singleLine = singleLine,
maxLines = maxLines,
interactionSource = interactionSource,
shape = shape,
colors = colors,
modifier = Modifier
.fillMaxWidth()
.height(height)
)
}
}
}