標籤:
在安卓中這兩個屬性經常用,特地來總結一下:
android:layout_gravity:XML 裡面的提示是這樣的,Standard gravity constant that a child supplies to its parent. [flag],我大致翻譯一下,一個由子view提供給父view用作指定位置的常量。
android:gravity:Specifies how to align the text by the view‘s x- and/or y-axis when the text is smaller than the view. [flag],文字有點長,大致意思就是該屬性是決定如何決定view的內容的一個屬性
android:layout_gravity 只能用於LinearLayout,在LinearLayout中,指定該布局才有效,即給控制項或者布局制定該屬性時,父布局必須是 LinearLayout才能指定,否則是沒有該屬性的,在xml裡面也沒有提示,特別的,當LinearLayout指定 android:orientation="vertical"時,android:layout_gravity只在水平方向有效;當 android:orientation="horizontal"時,改屬性只在垂直方向有效。
注意,如果子view未置中,可能是因為layout_width或者layout_height屬性為fill_parent了,改成wrap_content
1 LinearLayout裡嵌套RelativeLayout:有效,當時反過來該屬性就無效了 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="fill_parent" 4 android:layout_height="fill_parent" 5 android:orientation="vertical" > 6 7 <Button 8 android:layout_width="wrap_content" 9 android:layout_height="wrap_content"10 android:text="aaa" />11 12 <Button13 android:layout_width="wrap_content"14 android:layout_height="wrap_content"15 android:text="aaa" />16 17 <Button18 android:layout_width="wrap_content"19 android:layout_height="wrap_content"20 android:text="aaa" />21 22 <RelativeLayout23 android:gravity="center"24 android:layout_width="fill_parent"25 android:layout_height="fill_parent"26 android:layout_gravity="center_vertical" >27 28 29 <Button30 android:id="@+id/button1"31 android:layout_width="wrap_content"32 android:layout_height="wrap_content"33 android:text="Button" />34 </RelativeLayout>35 36 </LinearLayout>
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:layout_width="fill_parent" 3 android:layout_height="fill_parent" 4 android:orientation="horizontal" > 5 6 <Button 7 android:layout_width="wrap_content" 8 android:layout_height="wrap_content" 9 android:text="aaa" />10 11 <LinearLayout12 android:layout_gravity="center_vertical"13 android:layout_width="fill_parent"14 android:layout_height="wrap_content" >15 16 <Button17 android:layout_width="wrap_content"18 android:layout_height="wrap_content"19 android:text="aaa" />20 </LinearLayout>21 22 </LinearLayout>
android:layout_gravity和android:gravity