ConstraintLayout (約束布局)
? 在2016年由Google I/O推出,將成為主流布局樣式, 完全代替其他布局, 減少布局的層級(jí), 優(yōu)化渲染性能,作為非綁定(Unbundled)的支持庫(kù), 命名空間是app:, 即來(lái)源于本地的包命名空間. 最新版本是1.0.1(2017.4.21)
1. 添加依賴
dependencies {
compile 'com.android.support.constraint:constraint-layout:1.0.1'
}
2. 根據(jù)布局中的其他元素或視圖, 確定View在屏幕中的位置。
受到三類約束:
- 即其他視圖
- 父容器(parent)
- 基準(zhǔn)線(Guideline).
3. 如何使用:
- 添加名稱空間:
xmlns:app="http://schemas.android.com/apk/res-auto"
- 屬性的使用:
layout_constraint[本源位置]_[目標(biāo)位置]="[目標(biāo)ID]"
//eg:
app:layout_constraintBottom_toBottomOf="@+id/constraintLayout"
//約束當(dāng)前View的底部至目標(biāo)View的底部, 目標(biāo)View是constraintLayout. 即, 把當(dāng)前View的底部對(duì)齊到constraintLayout的底部.
- 常見的屬性:
| 屬性的使用 | 說(shuō)明 |
|---|---|
| app:layout_constraintLeft_toLeftOf="@+id/root" | 控件的左邊緣與root的左邊緣對(duì)齊 |
| app:layout_constraintRight_toRightOf="@+id/root" | 控件的右邊緣與root的右邊緣對(duì)齊 |
| app:layout_constraintBottom_toBottomOf="@+id/root" | 控件的下邊緣與root的下邊緣對(duì)齊 |
| app:layout_constraintTop_toTopOf="@+id/=root" | 控件的上邊緣與root的上邊緣對(duì)齊 |
居中對(duì)齊:4個(gè)屬性同時(shí)使用,就完成了居中對(duì)齊
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_head"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/dog"
app:layout_constraintBottom_toBottomOf="@id/root"
app:layout_constraintLeft_toLeftOf="@+id/root"
app:layout_constraintRight_toRightOf="@+id/root"
app:layout_constraintTop_toTopOf="@id/root" />
</android.support.constraint.ConstraintLayout>