【问题标题】:Avoid side padding from particular child item of LazyColumn in jetpack compose避免在 Jetpack Compose 中使用 LazyColumn 的特定子项进行侧边填充
【发布时间】:2023-02-04 04:40:42
【问题描述】:

我想删除 LazyColum 中特定子项的侧边距。我在 post 的帮助下用 xml 解决了这个问题。我在 Jetpack Compose 中有相同的场景。我正在使用 compose_bom = "2022.11.00" 的 BOM 版本材料 3.

    Card(shape = RoundedCornerShape(6.dp),) {
        Column(modifier.background(Color.White)) {
            LazyColumn(
                contentPadding = PaddingValues(all =16.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp),
            ) {
                item {
                    Text(
                        text = "Device Header",
                        modifier = Modifier.padding(top = 10.dp),
                        style = headerTextStyle
                    )
                }

                item {
                    Divider() // remove padding from side in here
                }
            }
        }
    }

实际产量

预期产出

【问题讨论】:

    标签: android kotlin android-jetpack-compose android-jetpack android-jetpack-compose-layout


    【解决方案1】:

    在 Compose 中你不能使用负填充在孩子中减少父容器应用的填充。您可以使用offset带有负值的修饰符,但它会将Divider移到左侧。

    你可以使用layout修改器应用增加宽度的水平偏移。

    就像是:

    LazyColumn(
        Modifier.background(Yellow),
        contentPadding = PaddingValues(all = 16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        //...
    
        item {
            val sidePadding = (-8).dp
    
     
            Divider(modifier = Modifier
                .layout { measurable, constraints ->
                    // Measure the composable adding the side padding*2 (left+right)
                    val placeable =
                        measurable.measure(constraints.offset(horizontal = -sidePadding.roundToPx() * 2))
    
                    //increase the width adding the side padding*2
                    layout(
                        placeable.width + sidePadding.roundToPx() * 2,
                        placeable.height
                    ) {
                        // Where the composable gets placed
                        placeable.place(+sidePadding.roundToPx(), 0)
                    }
    
                }
            )          
            
        }
    }
    

    在这里,您可以找到带有不带修饰符的 Divider() 的输出,以及带有 layout 修饰符的 Divider 的输出。

    【讨论】:

    • 我怎样才能固定在右侧?你能详细解释一下我们在layout 中所做的事情吗?
    • @VivekModi 这取决于您想在右侧实现什么。布局修饰符测量应用水平偏移量 (leftPadding) 的可组合项,然后放置增加 +leftPadding.roundToPx() 宽度的内容。根据您要实现的目标更改宽度。
    • 是的,我试图增加宽度,但它只增加了左侧,我想在右侧增加同样的东西。那么如果我创建 rightPadding 值应该放在哪里呢?
    • @VivekModi 我已经更新了答案,增加了两侧宽度相同的分隔线。
    猜你喜欢
    • 2022-11-05
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 2022-10-04
    • 2021-06-01
    • 2022-09-26
    相关资源
    最近更新 更多