android:layout_gravity和android:gravity

 

 

在安卓中这两个属性经常用,特地来总结一下:

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     <Button
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
15         android:text="aaa" />
16 
17     <Button
18         android:layout_width="wrap_content"
19         android:layout_height="wrap_content"
20         android:text="aaa" />
21 
22     <RelativeLayout
23         android:gravity="center"
24         android:layout_width="fill_parent"
25         android:layout_height="fill_parent"
26         android:layout_gravity="center_vertical" >
27 
28 
29         <Button
30             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     <LinearLayout
12         android:layout_gravity="center_vertical"
13         android:layout_width="fill_parent"
14         android:layout_height="wrap_content" >
15 
16         <Button
17             android:layout_width="wrap_content"
18             android:layout_height="wrap_content"
19             android:text="aaa" />
20     </LinearLayout>
21 
22 </LinearLayout>

 


 

posted @ 2016-06-30 06:23  ft039x  阅读(179)  评论(0编辑  收藏  举报
TOP