默认情况下不给控件设置属性的话,控件是靠着父元素的左边和上边。
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button1" />
相对于父元素的属性
align:对齐
android:layout_alignParentLeft=”true”:在父元素内左边,位置如上图
android:layout_alignParentRight=”true”:在父元素内右边,右上角
android:layout_alignParentTop=”true”:在父元素内顶部,左上角
android:layout_alignParentBottom=”true”:在父元素内底部,左下角
相对于兄弟元素的属性
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="button1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/button1" 在指定View的右边
android:text="button2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/button1" 在指定View的左边
android:text="button3" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button1" 在指定View的下方
android:text="button4" />
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/button1" 在指定View的上方
android:text="button5" />
对齐方式
android:layout_centerInParent=”true”:居中布局,在LinearLayout中无效
android:layout_centerVertical=”true”:垂直居中布局
android:layout_centerHorizontal=”true”:水平居中布局
android:layout_alignTop=”@id/xxx”:当前控件的上边界与指定View的上边界一致
android:layout_alignBottom=”@id/xxx”:当前控件的下边界与指定View下边界一致
android:layout_alignLeft=”@id/xxx”:当前控件的左边界与指定View的左边界一致
android:layout_alignRight=”@id/xxx”:当前控件的右边界与指定View的右边界一致
间隔
margin:边缘
padding:填充
一个控件跟另一个控件的距离叫边距(margin), 控件跟自己内容的距离叫填充(padding),如果一个布局里只有一个控件,那么margin就是与父布局的距离,如果控件在左上角,只有Top和Left有效果。
android:layout_marginBottom=”“;
android:layout_marginLeft=”“;
android:layout_marginRight =”“;
android:layout_marginTop=”“;
android:paddingBottom=”“;
android:paddingLeft=”“;
android:paddingRight =”“;
android:paddingTop=”“;
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="40dp" //这个控件和他下方的控件距离为40dp
android:text="button1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button1"
android:text="button2" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:paddingLeft="40dp"
android:text="button1" />