android:layout_gravity和android:gravity的區別

1.首先來看看android:layout_gravity和android:gravity的使用區別。

android:gravity:

這個是針對控件裏的元素來說的,用來控制元素在該控件裏的顯示位置。例如,在一個Button按鈕控件中設置如下兩個屬性,

android:gravity="left"和android:text="提交",這時Button上的文字“提交”將會位於Button的左部。


android:layout_gravity:

這個是針對控件本身而言,用來控制該控件在包含該控件的父控件中的位置。同樣,當我們在Button按鈕控件中設置android:layout_gravity="left"屬性時,表示該Button按鈕將位於界面的左部。


2.屬性值:

這兩個屬性可選的值有:top、bottom、left、right、center_vertical、fill_vertical、center_horizontal、fill_horizontal、center、fill、clip_vertical。

一個屬性可以包含多個值,需用“|”分開。其含義如下:

top 將對象放在其容器的頂部,不改變其大小.
bottom 將對象放在其容器的底部,不改變其大小.
left 將對象放在其容器的左側,不改變其大小.
right 將對象放在其容器的右側,不改變其大小.
center_vertical 將對象縱向居中,不改變其大小. 
垂直對齊方式:垂直方向上居中對齊。
fill_vertical 必要的時候增加對象的縱向大小,以完全充滿其容器. 
垂直方向填充
center_horizontal 將對象橫向居中,不改變其大小. 
水平對齊方式:水平方向上居中對齊
fill_horizontal 必要的時候增加對象的橫向大小,以完全充滿其容器. 
水平方向填充
center 將對象橫縱居中,不改變其大小.
fill 必要的時候增加對象的橫縱向大小,以完全充滿其容器.
clip_vertical

附加選項,用於按照容器的邊來剪切對象的頂部和/或底部的內容. 剪切基於其縱向對齊設置:頂部對齊時,剪切底部;底部對齊時剪切頂部;除此之外剪切頂部和底部.

垂直方向裁剪

clip_horizontal

附加選項,用於按照容器的邊來剪切對象的左側和/或右側的內容. 剪切基於其橫向對齊設置:左側對齊時,剪切右側;右側對齊時剪切左側;除此之外剪切左側和右側.

水平方向裁剪


我們主要來看看center_vertical和center_horizontal兩個屬性值,center_vertical是指將對象在垂直方向上居中對齊,即在從上到下的方向上選擇中間的位置放好;center_horizontal是指將對象水平方向上居中對齊,即在從左到右的方向上選擇中間的位置放好

3.特殊情況

當我們採用LinearLayout佈局時,有以下特殊情況需要我們注意:

(1)當 android:orientation="vertical"  時, android:layout_gravity只有水平方向的設置才起作用,垂直方向的設置不起作用。即:left,right,center_horizontal 是生效的。

(2)當 android:orientation="horizontal" 時, android:layout_gravity只有垂直方向的設置才起作用,水平方向的設置不起作用。即:top,bottom,center_vertical 是生效的。


下面以一個例子說明:(本例來源於:http://blog.csdn.net/dekunchenivan/article/details/6718678


  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.     <TextView    
  8.         android:layout_width="100dip"   
  9.         android:layout_height="100dip"  
  10.         android:layout_gravity="bottom|center_horizontal"  
  11.         android:gravity="center|bottom"  
  12.         android:background="#00FF00"  
  13.         android:text="@string/textview"  
  14.         />  
  15.   
  16.     <Button  
  17.         android:layout_width="100dip"  
  18.         android:layout_height="100dip"  
  19.         android:layout_gravity="bottom|left"  
  20.         android:gravity="left|top"  
  21.         android:background="#FF0000"  
  22.         android:text="@string/button"  
  23.         />  
  24. </LinearLayout>  

其效果如圖:  





在TextView中,我們設置了android:layout_gravity="bottom|center_horizontal"  ,但該TextView並沒有顯示在屏幕的下方正中央,表明只有center_horizontal屬性起了作用,這正是因爲我們使用了LinearLayout佈局,並且其android:orientation="vertical",只有水平方向的設置纔會起作用,其他方向則會失效。同樣,Button也一樣。


發佈了0 篇原創文章 · 獲贊 3 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章