【问题标题】:Problems with Compose BasicTextField:Compose BasicTextField 的问题:
【发布时间】:2021-06-21 03:25:01
【问题描述】:

现在我有一个自定义的 Compose 输入框。 BasicTextField,但无论如何我都无法将输入字体居中。我只能通过Box的offset属性在x方向上进行偏移。

之所以要自定义输入框,是因为我需要一个固定高度的输入框和字体大小。但是当高度不够时,文本字段无法输入。

请帮帮我,我更喜欢使用 TextField 来编写固定高度的输入框。但是在网站上没有找到合适的解决方案。

这是我的自定义代码:

@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,
    offsetDp: Dp = 10.dp,
    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(x = offsetDp),
                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 kotlin android-view android-jetpack-compose


    【解决方案1】:

    你可以使用类似的东西:

    BasicTextField(
        textStyle = LocalTextStyle.current.copy(textAlign = TextAlign.Center),
        decorationBox = {innerTextField ->
            Box(
                contentAlignment = Alignment.Center 
            ) {
                if (text.isEmpty()) {
                    Text(
                        text = "placeHolder",
                    )
                }
                innerTextField()
            }
        }
    )
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 2021-07-07
      • 2022-12-05
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 2022-06-20
      • 1970-01-01
      相关资源
      最近更新 更多