相对布局(RelativeLayout)

2019-07-03  本文已影响0人  Fastcv

前言

相对布局可以让子控件相对于兄弟控件或父控件进行布局,可以设置子控件相对于兄弟控件或父控件进行上下左右对齐。RelativeLayout能替换一些嵌套视图,当我们用LinearLayout来实现一个简单的布局但又使用了过多的嵌套时,就可以考虑使用RelativeLayout重新布局。(结合大佬们的博客总结的,如有侵权,麻烦联系我删除此文章)

属性

常用属性:

1、相对于父控件

属性 说明
android:layout_alignParentTop 控件的顶部与父控件的顶部对齐
android:layout_alignParentBottom 控件的底部与父控件的底部对齐
android:layout_alignParentLeft 控件的左部与父控件的左部对齐
android:layout_alignParentRight 控件的右部与父控件的右部对齐

2、相对给定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的右边缘对齐

3、居中

属性 说明
android:layout_centerHorizontal 水平居中
android:layout_centerVertical 垂直居中
android:layout_centerInParent 父控件的中央

举例

relayout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="100dp"
        android:id="@+id/bt2"
        android:text="bt2"
        android:layout_above="@+id/bt1"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="100dp"
        android:id="@+id/bt3"
        android:text="bt3"
        android:layout_toRightOf="@+id/bt1"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="100dp"
        android:id="@+id/bt4"
        android:text="bt4"
        android:layout_below="@+id/bt1"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="100dp"
        android:id="@+id/bt5"
        android:text="bt5"
        android:layout_toLeftOf="@+id/bt1"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="100dp"
        android:layout_centerInParent="true"
        android:id="@+id/bt1"
        android:text="bt1"
        android:layout_height="wrap_content" />

</RelativeLayout>

示意图:


realayout.png

附加

上一篇 下一篇

猜你喜欢

热点阅读