在進行UI布局的時候,可能經常會用到 android:gravity 和 android:layout_Gravity 這兩個屬性。
關于這兩個屬性的差別,網上已經有很多人進行了說明,這邊再簡單說一下。 (資料來自網絡)
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中居右顯示。看下效果:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIml2Zukmc0EDMzATO5EzMwMTMfBzLclTMvwFNwETMwIzLcRnbl1GajFGd0F2LcRXZu5ibkN3YukGavw1LcpDc0RHaiojIsJye.gif)
正如我們所看到的,在EditText中,其中的文字已經居中顯示了,而EditText元件自己也對齊到了LinearLayout的右側。
附上布局檔案:
[xhtml] view plain copy print ?
- <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"/>