【Android佈局】在程序中設置android:gravity 和 android:layout_Gravity屬性

LinearLayout有兩個很是類似的屬性:html

android:gravity與android:layout_gravity。android

 

他們的區別在於:佈局

 

android:gravity 屬性是對該view中內容的限定.好比一個button 上面的text. 你能夠設置該text 相對於view的靠左,靠右等位置.

android:layout_gravity是用來設置該view相對與父view 的位置.好比一個button 在linearlayout裏,你想把該button放在linearlayout裏靠左、靠右等位置就能夠經過該屬性設置. spa

 

即android:gravity用於設置View中內容相對於View組件的對齊方式,而android:layout_gravity用於設置View組件相對於Container的對齊方式。.net

 

原理跟android:paddingLeft、android:layout_marginLeft有點相似。若是在按鈕上同時設置這兩個屬性。xml

android:paddingLeft="30px"  按鈕上設置的內容離按鈕左邊邊界30個像素
android:layout_marginLeft="30px"  整個按鈕離左邊設置的內容30個像素htm

 


下面回到正題, 咱們能夠經過設置android:gravity="center"來讓EditText中的文字在EditText組件中居中顯示;同時咱們設置EditText的android:layout_gravity="right"來讓EditText組件在LinearLayout中居右顯示。看下效果:blog

 

 

 

正如咱們所看到的,在EditText中,其中的文字已經居中顯示了,而EditText組件本身也對齊到了LinearLayout的右側。ip

 

附上佈局文件:get

 

 

[xhtml]  view plain  copy
 
  1. <LinearLayout  
  2.    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.     <EditText  
  7.         android:layout_width="wrap_content"  
  8.         android:gravity="center"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="one"  
  11.         android:layout_gravity="right"/>  
  12. </LinearLayout>  
相關文章
相關標籤/搜索