RelativeLayout是一个相对布局类。首先RelativeLayout是一个容器,它里边的元素,如Button按钮等的位置是按照相对位置来计算的,例如,有两个Button按钮都布局在一个RelativeLayout里边,我们可以定义第二个Button在第一个Button的上边或者是右边。但到底第二个Button在什么位置呢,它还是依赖于第一个Button的位置。需要注意的是,出于性能上的考虑,对于相对布局的精确位置的计算只会执行一次,所以,如果一个可视化组件B依赖A,那么必须要让A出现在B的前边。
实例:LayoutDemo
运行效果:
代码清单:
布局文件:relative_layout.xml
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 设置此组件和指定组件高度齐平
实例:LayoutDemo
运行效果:
代码清单:
布局文件: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="请输入用户名:"
/>
<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 设置此组件和指定组件高度齐平