第二章 UI组件
2-1 布局管理器
2-1-2 RelativeLayout
相对布局是参照的概念,相对的
常用属性(线性布局常用的那些,相对布局也有,除了那些之外,还有以下几个相对布局特有的):
- android:layout_toLeftOf
- android:layout_toRightOf
- android:layout_alignBottom 将该控件的底部边缘与给定ID的底部边缘对齐;
- android:layout_alignParentBottom 将该控件的底部边缘与父控件的底部边缘对齐;
- android:layout_alignTop 将该控件的顶部边缘与给定ID的顶部边缘对齐;
- android:layout_below 将该控件的底部置于给定ID的控件之下;
- android:layout_above 将该控件的底部置于给定ID的控件之上;
- android:layout_centerHorizontal=“true” 将本控件置于父控件水平方向的中心位置
- android:layout_centerVertical=“true” 将本控件置于父控件垂直方向的中心位置
- android:layout_centerInParent=“true” 将控件置于父控件的中心位置
示例:
先写一个初始的:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/view_1"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#000000"/>
</RelativeLayout>
(默认从左从上对齐)
下面改成与父控件的底部对齐:
如果要再加一个View2,且位置在View1的右边:
<View
android:id="@+id/view_2"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#FF0033"
android:layout_toRightOf="@+id/view_1"/>
要在下面的话就换成
android:layout_below="@+id/view_1"
在下面再写一个线性布局,设了内边距15dp,在线性布局里写一个View,一个相对布局,该相对布局设了内边距15dp,然后在该相对布局里再写一个View3,一个View4
<LinearLayout
android:id="@+id/ll_1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="@id/view_2"
android:orientation="horizontal"
android:background="#0066FF"
android:padding="15dp">
<View
android:layout_width="100dp"
android:layout_height="match_parent"
android:background="#FFFF00"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:padding="15dp">
<View
android:id="@+id/view_3"
android:layout_width="100dp"
android:layout_height="match_parent"
android:background="#FF9900"/>
<View
android:id="@+id/view_4"
android:layout_width="100dp"
android:layout_height="match_parent"
android:background="#FF9900"
android:layout_toRightOf="@id/view_3"
android:layout_marginLeft="10dp"/>
</RelativeLayout>
</LinearLayout>