Android Jetpack Compose中LinearLayout的替代方案是什么?

3

在Android Jetpack Compose中,我可以使用什么代替LinearLayout?最好能提供一个示例,演示如何使用新的API替换常用的LinearLayout功能。

1个回答

14

LinearLayout对应于Compose中的RowColumn组合。

如果您要显示大量项目,请查看LazyRowLazyColumn,它们仅显示像RecyclerView一样可见的项目,但您可以像使用Row和Column一样使用它们。请参见Jetpack Compose中的RecyclerView或ListView等效物是什么?以获取示例。

让我们比较一下LinearLayout API和Row、Column:


android:orientation (LinearLayout)
正如你所猜测的,<LinearLayout android:orientation="vertical" ...> 等同于 Column {},而 <LinearLayout android:orientation="horizontal" ...> 等同于 Row {}


android:gravity (LinearLayout)
ColumnhorizontalAlignmentverticalArrangement参数,RowverticalAlignmenthorizontalArrangement参数。例如:

<LinearLayout ...
    android:orientation="vertical"
    android:gravity="end|center">
  ...
</LinearLayout>

等同于

Column(
    ...
    horizontalAlignment = Alignment.End,
    verticalArrangement = Arrangement.Center
) { ... }

android:layout_gravity (LinearLayout.LayoutParams)
查看行的align和列的align修饰符,如果设置了容器对齐方式,则覆盖容器对齐方式。还有更高级的修饰符,例如行的alignByBaseline,请参阅文档以获取更多详细信息。例如:

<LinearLayout ...
    android:orientation="vertical"
    android:gravity="end">

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="first" />

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:text="second" /> 

</LinearLayout>

等于

Column(
    ...
    horizontalAlignment = Alignment.End,
) {
    // this item is aligned to the end according to the column's alignment
    Text("first")
    // but this one is aligned to the start because it overrides the alignment
    Text("second", modifier = Modifier.align(Alignment.Start))
}

android:layout_weight (LinearLayout.LayoutParams)
参见行的weight和列的weight修饰符。例如

<LinearLayout android:orientation="horizontal" ...>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:text="first" />
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:text="second" />
</LinearLayout>

等于
Row {
    Text("first", modifier = Modifier.weight(1.0f))
    Text("second", modifier = Modifier.weight(2.0f))
}

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