在Android开发中,layout_gravity属性用于指定子视图在其父布局中的位置。通过灵活使用layout_gravity,你可以创建出各种不同的布局效果。以下是一些常见的使用方法:
layout_gravity="fill"会让子视图填充其父布局的所有可用空间。
<LinearLayout
    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:layout_gravity="fill"
        android:text="This TextView will fill the entire layout." />
</LinearLayout>
layout_gravity="center"会让子视图在其父布局中居中对齐。
<LinearLayout
    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:layout_gravity="center"
        android:text="This TextView will be centered." />
</LinearLayout>
layout_gravity="top"会让子视图在其父布局的顶部对齐。
<LinearLayout
    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:layout_gravity="top"
        android:text="This TextView will be aligned to the top." />
</LinearLayout>
layout_gravity="bottom"会让子视图在其父布局的底部对齐。
<LinearLayout
    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:layout_gravity="bottom"
        android:text="This TextView will be aligned to the bottom." />
</LinearLayout>
layout_gravity="left"和layout_gravity="right"分别会让子视图在其父布局的左侧和右侧对齐。
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:text="This TextView will be aligned to the left." />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="This TextView will be aligned to the right." />
</LinearLayout>
你还可以使用layout_gravity结合layout_margin来精确控制子视图的位置。
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="16dp"
        android:text="This TextView will be centered vertically and have a margin on the left." />
</LinearLayout>
通过这些方法,你可以灵活地使用layout_gravity属性来实现各种布局需求。