也談layout_gravity和gravity

轉載自:http://www.cnblogs.com/olvo/archive/2012/05/21/2511632.html

相信對於Android的初學者來說,大家都曾經被layout裏這兩個極其相似的屬性迷惑過。

簡單使用一下搜索工具,我們就不難找到下面這樣的答案:

layout_gravity 表示組件自身在父組件中的位置
gravity             表示組件的子組件在組件中的位置

看似很簡單嘛~)

貌似大夥瞅一眼就明白了。今天我要說的就是這貌似瞅一眼就明白的道理。
爲什麼這麼簡單的道理,總有同學會發現,在“某些時候”,layout_gravity這個屬性不好使了,失去了它應有的作用。

於是同學們又開始使用搜索工具,一邊還不停的罵:Google做的這個layout真他媽的不好使!
下面我們就網上找來的一個例子來簡單描述一種layout_gravity失效的情況。

    <?xml version="1.0" encoding="utf-8"?>
    <!-- android:gravity設置了按鈕上面的文字的顯示位置,而android:layout_gravity設置了按鈕在佈局中的顯示位置。 –>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <Button android:layout_width="250dip"
                    android:gravity="right"
                    android:layout_height="wrap_content"
                    android:text="我居右顯示"
                    android:layout_gravity="right" />;
    </LinearLayout>


這段代碼的展現效果如下:


然後我們再看下面這段代碼:

    <?xml version="1.0" encoding="utf-8"?>
    <!-- android:gravity設置了按鈕上面的文字的顯示位置,而android:layout_gravity設置了按鈕在佈局中的顯示位置。 –>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <Button android:layout_width="250dip"
                    android:gravity="right"
                    android:layout_height="wrap_content"
                    android:text="我居右顯示"
                    android:layout_gravity="right" />
    </LinearLayout>


複製代碼

這段代碼我們一樣設置了android:layout_gravity="right",但是它的展現效果卻是下面這樣的:

於是我們前面所說的情況就發生了,“Google做的這個layout真他媽的不好使!”

問題究竟出在哪裏了呢?
細心一點的同學就會發現,下面的這段代碼,最外層的LinearLayout少了這樣一個屬性:androidrientation="vertical"
不錯,正是缺少了這個屬性才導致了android:layout_gravity="right"的失效。
因爲LinearLayout默認的是:androidrientation="horizontal" "

也就是說,只有在作爲父layout的LinearLayout是androidrientation="vertical" 的時候,android:layout_gravity="right"纔會生效。

到這裏本次“講座”可以結束了嗎? No!

看完上面的內容,有同學也許還會發現,當外層的LinearLayout爲androidrientation="vertical" 的時候,android:layout_gravity="bottom"失效了

看到這裏相信大家都明白了

下面我們還需要做一個簡單的總結:
當作爲父layout的LinearLayout的屬性爲androidrientation="vertical" 的時候,android:layout_gravity="?"這裏設爲橫向的時候才能生效。比如:left,right,center_horizontal等

當作爲父layout的LinearLayout的屬性爲androidrientation="horizental" 的時候,android:layout_gravity="?"這裏設爲縱向的時候才能生效。比如:top,bottom,center_vertical等;

有一個比較特殊的是center,不管是橫向還是縱向的時候,它總有一個方向起作用




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章