【问题标题】:Align Textfield label to start of underbar using Jetpack Compose使用 Jetpack Compose 将文本字段标签与下划线的开头对齐
【发布时间】:2021-05-31 05:57:30
【问题描述】:

默认情况下,Textfield 的标签不与下划线的起始位置对齐。标签文本前似乎有一些空白。

这就是我的文本字段的样子:

我希望我的文本字段的标签与下划线的起始位置对齐。我如何做到这一点?

【问题讨论】:

    标签: android textfield android-jetpack-compose android-jetpack-compose-text


    【解决方案1】:

    使用1.0.0(使用1.0.0-beta07 测试),TextField 遵循材料指南,并且没有内置参数可以更改此行为。
    您应该使用带有特定样式的BasicTextField

    否则你可以使用drawBehind修饰符:

    val interactionSource = remember { MutableInteractionSource() }
    val isFocused by interactionSource.collectIsFocusedAsState()
    
    val IndicatorUnfocusedWidth = 1.dp
    val IndicatorFocusedWidth = 2.dp
    val TextFieldPadding = 16.dp
    
    val indicatorColor = if (isFocused) Color.Red else Color.Gray
    val indicatorWidth = if (isFocused) IndicatorFocusedWidth else IndicatorUnfocusedWidth
    
    TextField(
        value = text,
        onValueChange = {
            text = it },
        label={Text("Label")},
        interactionSource = interactionSource,
        modifier = Modifier
            .drawBehind {
                val strokeWidth = indicatorWidth.value * density
                val y = size.height - strokeWidth / 2
                drawLine(
                    indicatorColor,
                    Offset(TextFieldPadding.toPx(), y),
                    Offset(size.width - TextFieldPadding.toPx(), y),
                    strokeWidth
                )
            },
        colors = TextFieldDefaults.textFieldColors(
            backgroundColor = Color.Transparent,
            focusedIndicatorColor =  Transparent,
            unfocusedIndicatorColor = Transparent,
            disabledIndicatorColor = Transparent
        )
    )
    

    【讨论】:

      猜你喜欢
      • 2011-03-07
      • 1970-01-01
      • 2022-11-06
      • 2020-01-27
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 2021-10-01
      相关资源
      最近更新 更多