標籤:-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
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <EditText
- android:layout_width="wrap_content"
- android:gravity="center"
- android:layout_height="wrap_content"
- android:text="one"
- android:layout_gravity="right"/>
- </LinearLayout>
【Android布局】在程式中設定android:gravity 和 android:layout_Gravity屬性