Android属性 gravity, layout_gravity, padding, layout_margin 及 关于gravity/layout_gravity的一个Demo

1. android:gravity

对内的相对位置-----用来设置该view的内容在该View内的相对位置 (靠左,靠右,靠上, 靠下, 居中...,不是具体数值).

(官方的解释是:

  • gravity---Specifies how to place the content of an object, both on the x- and y-axis, within the object itself.
  • 数值center的含义---Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.)

2. android:layout_gravity

对外的相对位置-----用来设置该view在其父view内的相对位置 (靠左,靠右,靠上, 靠下, 居中...,不是具体数值).

(官方的解释是:

  • layout_gravity---Standard gravity constant that a child can supply to its parent. Defines how to place the view, both its x- and y-axis, within its parent view group.
  • 数值center的含义---Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.)

3. android:padding

对内的绝对位置-----用来设置该view的内容与该view的某一个边框或四个边框之间的距离数值 (是个具体数值).

一个view的尺寸既包括该view的内容, 又包括padding值.

4. android:layout_margin

对外的绝对位置-----用来设置该view与其父view的某一个边框或四个边框之间的距离数值 (是个具体数值).

但请注意:
如果要让一个子控件位于其父控件的水平和垂直居中的位置,  通常会想到
让父控件使用RelativeLayout, 并设定子控件的属性 android:layout_centerInParent="true". 但如果还要求该子控件的宽度与父控件的宽度成一定比例 (比如: 占父控件宽度的一半),  那么这时只能考虑让父控件使用水平方向的 LinearLayout 并设定其属性android:weightSum, 子控件的宽度设为0dp, 并设定属性 android:layout_weight 等于父控件android:weightSum属性数值的一半. 那么这时候又要求子控件在父控件内水平和垂直两个方向都居中, 我们可能会想到有两种解决方法:

  1. 设定父控件LinearLayout的属性 android:gravity="center"
  2. 设定子控件的属性 android:layout_gravity="center".

但是, 在实际使用中, 会发现,  前者有效, 后者无效.  即: 只有设定LinearLayout 的属性 android:gravity="center" 才能满足该位置要求.

下面分别演示两种布局方式的效果:

1.  设定父控件LinearLayout的 android:gravity="center"

布局文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

 android:layout_width="fill_parent"

 android:layout_height="fill_parent"

 android:orientation="horizontal"

 android:gravity="center"

 android:weightSum="1.0" >



    <Button  android:id="@+id/button1"

 android:layout_width="0dp"

 android:layout_height="wrap_content"

 android:layout_weight="0.5"

 android:text="Button" />

</LinearLayout>

该布局的竖直和水平显示效果分别如下:

image   image

由此可见, 上述布局已经成功实现了我们的想法.

2. 设定子控件的 android:layout_gravity="center".

布局文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

 android:layout_width="fill_parent"

 android:layout_height="fill_parent"

 android:orientation="horizontal"

 android:weightSum="1.0" >



    <Button  android:id="@+id/button1"

 android:layout_width="0dp"

 android:layout_height="wrap_content"

 android:layout_weight="0.5"

 android:layout_gravity="center"

 android:text="Button" />

</LinearLayout>

该布局的竖直和水平显示效果图分别如下:

image  image

可见, 子控件的宽度确实是父控件宽度的一半, 但子控件的位置却不满足要求. 设定子控件的 layout_gravity="center"属性却只能让该子控件垂直方向居中, 而水平方向并未居中, 而是位于父控件的最左边. 该方案不能满足我们的需求, 我暂时还想不出原因, 估计是对API的理解还不够深入吧, 希望知道原因的朋友给些指点, 谢谢!

你可能感兴趣的:(android)