RelativeLayout是一个相对布局类。
首先RelativeLayout是一个容器,它里边的元素,如Buttonbutton等的位置是依照相对位置来计算的,比如,有两个Buttonbutton都布局在一个RelativeLayout里边。我们能够定义第二个Button在第一个Button的上边或者是右边。但究竟第二个Button在什么位置呢,它还是依赖于第一个Button的位置。需要注意的是。出于性能上的考虑。对于相对布局的精确位置的计算仅仅会运行一次。所以。假设一个可视化组件B依赖A,那么必需要让A出如今B的前边。
实例:LayoutDemo
执行效果:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvSGFuVGFuZ1NvbmdNaW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
代码清单:
布局文件:relative_layout.xml
<? 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="wrap_content"
android:padding="10dip"
>
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请输入username:"
/>
<EditText
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/label"
/>
<Button
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="取消"
/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/cancel"
android:layout_alignTop="@id/cancel"
android:text="确定"
/> </RelativeLayout>
Java源码文件:RelativeLayoutActivity.java
package com.rainsong.layoutdemo; import android.app.Activity;
import android.os.Bundle; public class RelativeLayoutActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.relative_layout);
}
}
API知识点
android:id 定义组件的id
android:layout_width 定义组件的宽度
android:layout_height 定义组件的高度
android:padding 填充
android:layout_below 将当前组件放置于指定组件的下方
android:layout_alignParentRight 和父容器的右边齐平
android:layout_marginLeft 右边距
android:layout_toLeftOf 设置此组件在指定组件的左边
android:layout_alignTop 设置此组件和指定组件高度齐平