如何使用Android Jetpack Compose将所有项目排列在一行上

3

我正在尝试在我的应用程序中使用Compose。

我想要绘制一个像下面这样的用户界面。

它有标题和带有开关的描述。

图片描述

我的代码如下:

@Composable
fun Switch2Lines(
    @StringRes title: Int,
    @StringRes desc: Int
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Column {
            Text(
                text = "Title",
                modifier = Modifier.padding(top = 16.dp),
                fontSize = 18.sp
            )
            Text(text = "Desc Desc Desc Desc Desc Desc Desc Desc Desc Desc")
        }
        Switch(
            checked = true,
            onCheckedChange = {},
            modifier = Modifier.wrapContentSize()
        )
        Spacer(modifier = Modifier.padding(16.dp))
    }
}

在此情况下,说明太长了。 因此,开关布局不正确。 我在开关末尾添加了Spacer,但它不起作用。 我该如何解决这个问题?我应该使用constraintlayout-compose吗?
1个回答

5
你可以移除 Spacer 并使用一个权重修饰符来替换你的 Column。
Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.padding(16.dp)
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = "Title",
                modifier = Modifier.padding(top = 16.dp),
                fontSize = 18.sp
            )
            Text(text = "Desc Desc Desc Desc Desc Desc Desc Desc Desc Desc")
        }
        Switch(
            checked = true,
            onCheckedChange = {},
            modifier = Modifier.wrapContentSize()
        )
    }

为了理解权重的工作原理,您可以在这里阅读文档。
/**
     * Size the element's width proportional to its [weight] relative to other weighted sibling
     * elements in the [Row]. The parent will divide the horizontal space remaining after measuring
     * unweighted child elements and distribute it according to this weight.
     * When [fill] is true, the element will be forced to occupy the whole width allocated to it.
     * Otherwise, the element is allowed to be smaller - this will result in [Row] being smaller,
     * as the unused allocated width will not be redistributed to other siblings.
     *
     * @param weight The proportional width to give to this element, as related to the total of
     * all weighted siblings. Must be positive.
     * @param fill When `true`, the element will occupy the whole width allocated.
     */
    @Stable
    fun Modifier.weight(
        /*@FloatRange(from = 0.0, fromInclusive = false)*/
        weight: Float,
        fill: Boolean = true
    ): Modifier

所以它首先测量非加权子元素(在本例中为Switch),然后将剩余空间分配给带权子元素。由于Column是此处唯一的子元素,任何权重值都应该适用。

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