Android SDK Tutorials系列 - Hello Views - Relative Layout

Relative Layout

RelativeLayout 是ViewGroup 的一种,它里面包含的View按照相对位置进行排列,可以指定一个View跟相邻View的位置关系(例如:在某个View的左边,或者下面);或者指定这个View相对于RelativeLayout这个容器的位置(例如底部,或者左边中间)。

RelativeLayout是一个很强大的工具,在设计用户界面的时候可以消除嵌套的ViewGroup。如果你在嵌套使用LinearLayout,你应该可以用单个的RelativeLayout来取代它。

  1. 创建一个工程:HelloRelativeLayout
  2. 打开res/layout/main.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="fill_parent">
        <TextView
            android:id="@+id/label"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Type here:"/>
        <EditText
            android:id="@+id/entry"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@android:drawable/editbox_background"
            android:layout_below="@id/label"/>
        <Button
            android:id="@+id/ok"
            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="OK" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/ok"
            android:layout_alignTop="@id/ok"
            android:text="Cancel" />
    </RelativeLayout>

    关注每一个android:layout_* 属性,例如layout_belowlayout_alignParentRight, 还有layout_toLeftOf。 使用RelativeLayout的时候,用这些属性来设置每个View的位置。这些属性的每一个都定义了一种相对位置。有些属性使用相邻View的资源ID来定义自己的相对位置。例如,最后一个Button,被摆放在资源ID ok (这是前一个Button)的左边,并和它上对齐。

    所有的布局属性都定义在 RelativeLayout.LayoutParams.


  3. 确保你在onCreate() 方法装载了这个布局:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    setContentView(int) 方法装载这个Activity的布局文件,资源ID — R.layout.main 指向res/layout/main.xml布局文件。

  4. 运行应用。

应该能看到下面的画面:

Hello RelativeLayout



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值