Android新主流布局 約束布局

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. 如何使用:
  1. 添加名稱空間:
xmlns:app="http://schemas.android.com/apk/res-auto"
  1. 屬性的使用:
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的底部.

  1. 常見的屬性:
屬性的使用 說(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>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容