您的位置:首页 > 移动开发 > Android开发

Android常用布局控件之RelativeLayout

2011-04-05 01:10 453 查看
我们使用LinearLayout和TableLayout可以满足开发应用程序界面基本的要求。但是有时候实现界面的时候不够灵活,我们还可以使用另外一种控件RelativeLayout。RelativeLayout是一种相对布局的控件,这个容器内部的子元素们可以使用彼此之间的相对位置或者和容器间的相对位置来进行定位,类似于网页设计中的CSS。在指定控件的位置时,我们需要指定这个控件与其它控件之间的相对位置关系,比如说与另一个控件的左边对齐,右对齐,位于另一个控件的上方,下方等等。一个控件可以指定与多个其它控件的相对位置。这样,我们就可以在设计位置灵活多变的界面时就会更加的方便。
Android RelativeLayout 属性
// 相对于给定ID控件
android:layout_above 将该控件的底部置于给定ID的控件之上;
android:layout_below 将该控件的底部置于给定ID的控件之下;
android:layout_toLeftOf 将该控件的右边缘与给定ID的控件左边缘对齐;
android:layout_toRightOf 将该控件的左边缘与给定ID的控件右边缘对齐;

android:layout_alignBaseline 将该控件的baseline与给定ID的baseline对齐;
android:layout_alignTop 将该控件的顶部边缘与给定ID的顶部边缘对齐;
android:layout_alignBottom 将该控件的底部边缘与给定ID的底部边缘对齐;
android:layout_alignLeft 将该控件的左边缘与给定ID的左边缘对齐;
android:layout_alignRight 将该控件的右边缘与给定ID的右边缘对齐;
// 相对于父组件
android:layout_alignParentTop 如果为true,将该控件的顶部与其父控件的顶部对齐;
android:layout_alignParentBottom 如果为true,将该控件的底部与其父控件的底部对齐;
android:layout_alignParentLeft 如果为true,将该控件的左部与其父控件的左部对齐;
android:layout_alignParentRight 如果为true,将该控件的右部与其父控件的右部对齐;
// 居中
android:layout_centerHorizontal 如果为true,将该控件的置于水平居中;
android:layout_centerVertical 如果为true,将该控件的置于垂直居中;
android:layout_centerInParent 如果为true,将该控件的置于父控件的中央;
// 指定移动像素,值为px
android:layout_marginTop 上偏移的值;
android:layout_marginBottom 下偏移的值;
android:layout_marginLeft    左偏移的值;
android:layout_marginRight   右偏移的值;
示例:
]<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10px"
>
<TextView
android:id="@+id/textView"
android:text="TextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<!--没有对textView的位置做设置,默认为RelativeLayout容器的左上角  -->
<EditText
android:id="@+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:background="@android:drawable/editbox_background"
/>
<!--editText控件位于textView控件的下面-->
<Button
android:id="@+id/buttonSure"
android:text="确定"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editText"
android:layout_alignParentRight="true"
android:layout_marginLeft="10px"
/>
<!--buttonSure控件在editText控件的下面,并且于父容器的位置关系为右对齐。  android:layout_marginLeft="10px"
设置buttonSure控件的左外边距为10像素,即此控件的左边与其他控件相距10像素的距离-->
<Button
android:id="@+id/buttonCancel"
android:text="取消"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/buttonSure"
android:layout_alignTop="@id/buttonSure"
/>
<!--buttonCancel为相对于buttonSure的位置确定。buttonCancel控件的右边缘与buttonSure控件的左边缘对齐,
顶部边缘与buttonSure控件的 顶部边缘对齐-->
</RelativeLayout>

运行效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: