【Android布局】在程式中設定android:gravity 和 android:layout_Gravity屬性

來源:互聯網
上載者:User

標籤:-name   start   tail   name   效果   nta   pad   內容   com   

LinearLayout有兩個非常相似的屬性:

android:gravity與android:layout_gravity。

 

他們的區別在於:

 

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

android:layout_gravity是用來設定該view相對與父view 的位置.比如一個button 在linearlayout裡,你想把該button放在linearlayout裡靠左、靠右等位置就可以通過該屬性設定. 

 

即android:gravity用於設定View中內容相對於View組件的對齊,而android:layout_gravity用於設定View組件相對於Container的對齊。

 

原理跟android:paddingLeft、android:layout_marginLeft有點類似。如果在按鈕上同時設定這兩個屬性。

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

 


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

 

 

 

正如我們所看到的,在EditText中,其中的文字已經置中顯示了,而EditText組件自己也對齊到了LinearLayout的右側。

 

附上布局檔案:

 

 

[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>  

 

 

【Android布局】在程式中設定android:gravity 和 android:layout_Gravity屬性

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.