LinearLayout 是 Android 中最简单且最常用的布局之一,用于在水平或垂直方向上排列子视图。以下是 LinearLayout 的基本属性和使用方法:

基本属性:

  •  android:orientation: 定义 LinearLayout 的方向,可以是 horizontal(水平)或 vertical(垂直)。

  
  •  android:layout_width 和 android:layout_height: 分别定义 LinearLayout 的宽度和高度。


示例代码:

以下是一个简单的垂直方向的 LinearLayout 示例:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me" />

</LinearLayout>

在这个示例中,LinearLayout 包含三个子视图:两个 TextView 和一个 Button,所有的子视图都是垂直排列的。

重要概念:

  •  权重(Weight): 你可以使用 layout_weight 属性为子视图分配额外的空间。如果一个子视图的权重是2,而另一个是1,那么前者将占用比例为2:1的空间。

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Button 2" />

</LinearLayout>

在这个例子中,第一个按钮占用1份,第二个按钮占用2份,因此它们在水平方向上的空间比例是1:2。

注意事项:

  •  LinearLayout 是一个相对简单的布局,适用于简单的界面结构。

  •  对于更复杂的布局,可以考虑使用其他布局管理器,如 RelativeLayout、ConstraintLayout 等。


LinearLayout 是 Android 布局中的基础之一,了解如何使用它是 Android 开发的基础。


转载请注明出处:http://www.pingtaimeng.com/article/detail/15123/Android