文章目錄
- 介紹
- 常見屬性
- 根據父容器定位
- 根據兄弟組件定位
- 通用屬性
- margin 設置組件與父容器的邊距
- padding 設置組件內部元素的邊距
- 項目結構
- 主要代碼
介紹
RelativeLayout
是一個相對布局,如果不指定對齊位置,都是默認相對于父容器的左上角的開始布局
常見屬性
根據父容器定位
layout_alignParentLeft
:左對齊layout_alignParentRight
:右對齊layout_alignParentTop
:頂部對齊layout_alignParentBottom
:底部對齊layout_centerHorizontal
:水平居中layout_centerVertical
:垂直居中layout_centerInParent
:中間位置
根據兄弟組件定位
layout_toLeftOf
:放置于參考組件的左邊layout_toRightOf
:放置于參考組件的右邊layout_above
:放置于參考組件的上方layout_below
:放置于參考組件的下方layout_alignTop
:對齊參考組件的上邊界layout_alignBottom
:對齊參考組件的下邊界layout_alignLeft
:對齊參考組件的左邊界layout_alignRight
:對齊參考組件的右邊界
通用屬性
margin 設置組件與父容器的邊距
layout_margin
:上下左右偏移layout_marginLeft
:左偏移layout_marginRight
:右偏移layout_marginTop
:上偏移layout_marginBottom
:下偏移
padding 設置組件內部元素的邊距
項目結構
主要代碼
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:padding="50dp"android:layout_height="match_parent"><RelativeLayoutandroid:id="@+id/rl1"android:layout_width="100dp"android:layout_height="100dp"android:layout_centerInParent="true"android:background="#ff0000" /><!-- 這里發現如果不進行任何設置的話會將上面的布局進行一個覆蓋--><RelativeLayoutandroid:layout_width="100dp"android:layout_height="100dp"android:layout_toRightOf="@+id/rl1"android:background="#00ff00" /><RelativeLayoutandroid:layout_alignParentBottom="true"android:layout_marginLeft="100dp"android:layout_width="100dp"android:layout_height="100dp"android:background="#0000ff" /></RelativeLayout>