目录
一、线性布局 LinearLayout
二、相对布局 RelativeLayout
一、线性布局 LinearLayout
1.排列方向属性
(1)水平布局(默认)horizontal
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:src="@drawable/danger"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:src="@drawable/danger"
android:layout_width="100dp"
android:layout_height="100dp" />
</LinearLayout>
(2)垂直布局(vertical)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:src="@drawable/danger"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:src="@drawable/danger"
android:layout_width="100dp"
android:layout_height="100dp" />
</LinearLayout>
2.设置子控件的位置
属性 | 名称 | 代码 | 演示 |
center
|
水平垂直居中
|
android:gravity="center"
|
|
center_horizontal
|
水平居中
|
android:gravity="center_horizontal"
|
|
center_vertical
|
垂直居中
|
android:gravity="center_vertical"
|
|
top & bottom | 顶部 & 底部 | android:gravity="bottom" | |
left & right | 靠左 & 靠右 | android:gravity="right" |
|
3.子控件按照权重比分配空间
--在不等分的情况下,应将子控件宽(高)设为0dp,否则会计算不准确
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="right"
android:background="#ccc"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_weight="1"
android:background="#ff0"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="1"
android:background="#f00"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="1"
android:background="#0f0"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
二、相对布局 RelativeLayout
1.元素与元素的相对位置
android:layout_above | 设置本控件在某控件的上方 |
android:layout_below | 设置本控件在某控件的下方 |
android:layout_toLeftOf | 设置本控件在某控件的左边 |
android:layout_toRightOf | 设置本控件在某控件的右边 |
2.元素与容器的相对位置
android:layout_alignParentTop | 设置本控件在容器的顶部 |
android:layout_alignParentBottom | 设置本控件在容器的底部 |
android:layout_alignParentLeft | 设置本控件在容器的左边 |
android:layout_alignParentRight | 设置本控件在容器的右边 |
3.元素在容器中的居中关系
android:layout_centerHorizontal | 设置本控件在容器中水平居中 |
android:layout_centerVertical | 设置本控件在容器中垂直居中 |
android:layout_centerInParent | 设置本控件在容器中双向居中 |