Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

搞懂 Android 版面的相對性:layout_gravity 與 gravity 的差別

寫 Android 版面時最容易糊塗的一點,就是某個屬性到底是「相對父容器」、「相對子元素」,還是「只對自己有效」。最典型的例子莫過於 layout_gravity 與 gravity。以下用一個範例把思路理清。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <!--
        以下 LinearLayout 的 android:layout_gravity="center"
        相對於其父容器,因此水平居中
    -->
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="200dip"
        android:layout_height="60dip"
        android:layout_gravity="center"
        android:background="#00ff00"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="2dip"
            android:background="#ff0000"
            android:text="TextA" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#ff0000"
            android:text="TextB" />
    </LinearLayout>

    <!--
        以下 LinearLayout 的 android:gravity="bottom"
        表示其子 View 相對於該 LinearLayout 靠底對齊
    -->
    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="200dip"
        android:layout_height="60dip"
        android:layout_gravity="center"
        android:layout_marginTop="5dip"
        android:background="#ffff00"
        android:gravity="bottom"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/TextView03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="2dip"
            android:background="#ff0000"
            android:text="TextA" />

        <TextView
            android:id="@+id/TextView04"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#ff0000"
            android:text="TextB" />
    </LinearLayout>

</LinearLayout>

兩個綠色與黃色的方塊都水平居中,差別只在內部兩個紅色 TextA/TextB 的垂直位置:第一組預設置中,第二組被 gravity="bottom" 推到下方。

可以記住的命名規律

以 android:layout_xxx 開頭的屬性,通常描述「自身」在父容器中的定位,例如 layout_gravity="center" 是自己相對於父容器居中。

以 android:xxx 開頭的屬性,通常作用在子元素身上,例如 android:gravity 決定子 View 在容器內的對齊方式、android:orientation 決定排列方向。

這只是依命名歸納的通則,仍有例外:layout_marginRight 是自身相對父容器的外边距(在 RelativeLayout 中也可能牽涉兄弟元素),而 layout_height="60dip" 就只影響自己。遇到拿不準的屬性,最快的驗證方式就是改一個值、看畫面哪裡動了。

Copyright © Linux教程網 All Rights Reserved