重心設定

  • android:gravity
    1. 設定框架內子元件或子框架的放置位置。
    2. center 水平垂直皆置中。
    3. center_vertical 垂直置中。
    4. center_horizontal 水平置中。
    5. top 置頂。
    6. left 置左。
    7. bottom 置底。
    8. right 置右。

範例:垂直置中

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_vertical">

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

</LinearLayout>

範例:水平置中

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">

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

</LinearLayout>

範例:水平垂直皆置中

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

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

</LinearLayout>

範例;透過 OR 運算子組合重心

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="top|right">

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

</LinearLayout>