android - 如何为 Jetpack Compose 中的所有 child 设置 fillMaxWidth()?

标签 android android-jetpack-compose

我的问题:

我在同一个页面中有多个 TextField。我在我的 rootView(列)中给出了 fillMaxWidth()。 但是所有的 subview 宽度都将其作为 wrap_content。

我的代码:

Column(
    verticalArrangement = Arrangement.SpaceAround,
    modifier = Modifier
        .padding(10.dp)
        .fillMaxWidth()//I give the max width here
        .fillMaxHeight()
) {

       MyTextField1()// No modifiers used
       MyTextField2()
       ...
 }

输出:

enter image description here

我的问题:

我有 TextFields 列表。所以我想在 rootView 中处理代码简单性。 填充所有 subview 的宽度还有其他选择吗?

最佳答案

你不能添加一些不直接传递给所有 child 的修饰符。

但是使用 Layout 您可以创建自定义列,这将使所有子项填充最大宽度并在之间添加间距:

@Composable
fun ColumnFillChildrenWidth(
    modifier: Modifier = Modifier,
    spacing: Dp = 0.dp,
    content: @Composable () -> Unit,
) {
    Layout(
        content = content,
        modifier = modifier
    ) { measurables, constraints ->
        var yOffset = 0
        val placeablesWithOffset = measurables.map {  measurable ->
            val placeable = measurable.measure(constraints)
            val result = placeable to yOffset
            yOffset += placeable.height + spacing.toPx().toInt()
            result
        }

        val totalViewHeight = placeablesWithOffset.sumOf { it.first.height }
        val totalSpacing = ((measurables.size - 1) * spacing.toPx()).roundToInt()
        layout(
            width = constraints.maxWidth,
            height = totalViewHeight + totalSpacing
        ) {
            placeablesWithOffset.forEach {
                val (placeable, offset) = it
                placeable.place(0, offset)
            }
        }
    }
}

用法:

ColumnFillChildrenWidth(
    spacing = 20.dp,
    modifier = Modifier
        .fillMaxWidth()
        .padding(20.dp)
) {
    TextField(value = "", onValueChange = {})
    TextField(value = "", onValueChange = {})
    TextField(value = "", onValueChange = {})
}

结果:

关于android - 如何为 Jetpack Compose 中的所有 child 设置 fillMaxWidth()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68887918/

相关文章:

android - 在 Android 中,在 WorkManager 的 Worker 类中运行异步任务

android - 从警报对话框中删除黑色背景 - Android

android - 如何使用 Jetpack Compose 创建 HSL 饱和度和亮度变化渐变或画笔编辑器?

android - 喷气背包组成。导航 IllegalStateException

android - 尝试使用 Android Compose 和 Hilt 设置 Instrumented 测试时出现 ComponentActivity ClassNotFoundException

android - 向 LinearLayout 添加项目(并调整大小)

java - Android转义字符串中的字符

android - 在 JetPack Composable 中观察 LiveData

android - 具有 VerticalScroll 修饰符的 Column 内的 LazyColumn 会引发异常

java - 自定义adapterView多次调用getView函数更新 ListView 导致应用速度变慢