在Jetpack Compose中画线

70

使用XML布局,您可以使用带有彩色背景的View对象来绘制一条线。

<View
   android:width="match_parent"
   android:height="1dp"
   android:background="#000000" />

我们如何在Jetpack Compose中绘制水平或垂直线

2个回答

120

您可以使用

Divider Composable

方法生成以下类似的水平线

Divider(color = Color.Blue, thickness = 1.dp)

例子:

@Composable
fun drawLine(){
    MaterialTheme {

        VerticalScroller{
            Column(modifier = Spacing(16.dp), mainAxisSize = LayoutSize.Expand) {

                (0..3).forEachIndexed { index, i ->
                    Text(
                        text = "Draw Line !",
                        style = TextStyle(color = Color.DarkGray, fontSize = 22.sp)
                    )

                    Divider(color = Color.Blue, thickness = 2.dp)

                }
            }
        }

    }

}

4
“Divider”的“height”参数已更名为“thickness”。 - RickSanchez725
如果我们不想让它适应整个宽度怎么办?我只想要一个固定宽度和厚度的线条,并希望通过手势进行交互。 - Richard Onslow Roper
@MARSK,那么只需使用一个有颜色的盒子,这就是 Divider 内部所做的 - 它是一个超级简单的包装组合: Box(modifier.then(indentMod).fillMaxWidth().height(thickness).background(color = color)) - Luke Needham

41

要绘制一条线,您可以使用内置的androidx.compose.material.Divider,如果您使用androidx.compose.material或者使用与材料分隔符相同的方法创建自己的分隔符:

水平线

Column(
    // forces the column to be as wide as the widest child,
    // use .fillMaxWidth() to fill the parent instead
    // https://developer.android.com/jetpack/compose/layout#intrinsic-measurements
    modifier = Modifier.width(IntrinsicSize.Max)
) {
    Text("one", Modifier.padding(4.dp))

    // use the material divider
    Divider(color = Color.Red, thickness = 1.dp)

    Text("two", Modifier.padding(4.dp))

    // or replace it with a custom one
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(1.dp)
            .background(color = Color.Red)
    )

    Text("three", Modifier.padding(4.dp))
}

这里输入图像描述

竖线

Row(
    // forces the row to be as tall as the tallest child,
    // use .fillMaxHeight() to fill the parent instead
    // https://developer.android.com/jetpack/compose/layout#intrinsic-measurements
    modifier = Modifier.height(IntrinsicSize.Min)
) {
    Text("one", Modifier.padding(4.dp))

    // use the material divider
    Divider(
        color = Color.Red,
        modifier = Modifier
            .fillMaxHeight()
            .width(1.dp)
    )

    Text("two", Modifier.padding(4.dp))

    // or replace it with a custom one
    Box(
        modifier = Modifier
            .fillMaxHeight()
            .width(1.dp)
            .background(color = Color.Red)
    )

    Text("three", Modifier.padding(4.dp))
}

这是图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接