天天看點

Google I/O 2016 筆記之 Layout 新世界-ConstraintLayout

引子

首先來讓我們回顧一下 Android 目前已有的布局有哪些。

Google I/O 2016 筆記之 Layout 新世界-ConstraintLayout

我想大家使用比較多的應該是 

LinearLayout

 和 

RelativeLayout

 這兩種布局檔案.

實際在使用過程中,這兩種布局都會有各自的不足之處。比如你要用 

LinearLayout

 來實作一個複雜的布局,那麼就會産生一個很深的層級嵌套,而這顯然會帶來一定的性能問題。但是如果你要使用 RelativeLayout 來實作的話,你會發現無論在使用上還是布局編輯器上都非常難用。

有的小夥伴說,那 

LinearLayout

 和 

RelativeLayout

 混合使用不就可以解決問題了?

額...這...(兄弟,你不按套路出牌啊)

開個玩笑,因為作為Android官方來說,他們肯定有更優雅的方式嘛。這就是今天的主角-ConstraintLayout

ConstraintLayout 簡介

ConstraintLayout

 直譯的話,就是限制性布局.我們來看官方是怎麼來介紹它的:

A small , unbundled library compatible with API level 9 .

Designed to reduce nesting .

Designed to be used in Studio .

一句話,它很棒,你用不用!

可是我想知道 

ConstraintLayout

 到底是個什麼呢 ?

ConstraintLayout does what RelativeLayout does , but more .

對,你可以了解為一個增強版的 

RelativeLayout

 .

而相對于

RelativeLayout

ConstraintLayout

 則更加靈活,性能出衆,更主要的是,布局編輯器終于可以不那麼雞肋了 .

Google I/O 2016 筆記之 Layout 新世界-ConstraintLayout

看起來很Cool!是不是。

## ConstraintLayout 使用

準備工作

  • Android Studio 更新到2.2 preview
  • 添加 

    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha3'

     到 

    dependencies

     中

顯示

在布局編輯器中有兩種顯示方式:Design 和 Blueprint .

Google I/O 2016 筆記之 Layout 新世界-ConstraintLayout

Constraints

這部分内容參考(偷個懶)了官方指導教程 .

ConstraintLayout

 的重點在于Constraints,可以直譯為限制,或者關聯也可以。Constraints可以幫助你保持控件對齊. 你可以使用錨點(比如下圖展示的Button2的四個邊上圓點)來确定與之關聯控件之間的對齊規則. 例如, 設定一個從 button 2 的左邊到 button 1 的右邊的限制(見下圖),意味着控件 button 2 将會位于 button 1 右邊 56dp 處.

Google I/O 2016 筆記之 Layout 新世界-ConstraintLayout

操作類型的說明

Google I/O 2016 筆記之 Layout 新世界-ConstraintLayout

上圖中顯示了該控件所能操作的類型

調整控件大小的操作:

Google I/O 2016 筆記之 Layout 新世界-ConstraintLayout

建立控件之間邊關聯的操作:

Google I/O 2016 筆記之 Layout 新世界-ConstraintLayout

控件基準線限制的操作:

Google I/O 2016 筆記之 Layout 新世界-ConstraintLayout

示例

需要進一步了解或者感興趣的小夥伴可以直接去看看 

constraint-layout 這是Android官方提供的代碼示例.

關于 ConstraintLayout 的用法這裡隻簡單做個介紹,目前 

ConstraintLayout

 還處在一個快速疊代更新的階段,是以并不推薦在實際項目中去使用,就我個人的實際體驗上,确實還是存在着一些問題,當然這并不影響我們去了解它。

感想

正如 ConstraintLayout 官方介紹視訊中多次強調的那一句話:

Our job is to make your life easier.

我相信很快 ConstraintLayout 會給Android 開發者帶來一個不一樣的體驗 .

雖然我感覺它來的有點晚 ...