-
作用
ConstraintLayout是用來幫助我們用可視化的界面編寫XML文件的畸颅。
通常的XML文件不適合用可視化化的界面編寫狂芋,ConstraintLayout使得這一情況有了很大的改觀:
效果圖
ConstraintLayout可以通過可視化的操作微谓,生成XML代碼纽门。并且因為使用約束來定義不同控件的位置和他們的關(guān)系薛耻,因此,性能上也很不錯赏陵。
- 使用
Android Studio 生成的ConstraintLayout的代碼結(jié)構(gòu)
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mingpin.android.amazingmemory.AmazingMemoryActivity">
</android.support.constraint.ConstraintLayout>
buile.gradle module:app里的依賴:
dependencies {
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}
添加控件的約束饼齿,來滿足需要顯示的位置信息(預(yù)覽里出現(xiàn)的位置,不一定是運行時出現(xiàn)的位置)
-
單一控件添加約束時蝙搔,可以點擊控件缕溉,拖動控件的4個圓圈,會出現(xiàn)箭頭吃型,將其引導(dǎo)至邊界证鸥。
單一控件添加約束
根據(jù)需要,對4個邊界添加約束。
-
不同控件之間的約束
比如我們添加一個TextView控件枉层,讓其位于LinearLayout的上方64dp泉褐,那么我們選擇TextView控件,在它的下方的圈處點擊鸟蜡,使其箭頭指向ConstraintLayout的上方圓圈膜赃,調(diào)整TextView 的位置,使其距離ConstraintLayout 64dp揉忘。
多控件約束
XML代碼添加:
<TextView
android:id="@+id/textView"
android:layout_width="249dp"
android:layout_height="40dp"
android:layout_marginBottom="64dp"
android:gravity="center_vertical|center_horizontal"
android:visibility="visible"
app:layout_constraintBottom_toTopOf="@+id/linearLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
tools:text="@string/select_oneway" />
如果有其他控件跳座,以此方式建立約束。
-
約束刪除
刪除約束
將鼠標停在圓圈上泣矛,出現(xiàn)提示時躺坟,點擊左鍵就可以刪除了∪樾睿或者選中整個控件咪橙,點擊
<-X按鈕,可以刪除真?zhèn)€控件的約束(圖左下的<-X按鈕)虚倒。
Attribute的幾種屬性
-
Fixed
Fixed
Fixed實際效果:
Fixed效果 -
MatchConstraints
MatchConstraints
MatchConstraints效果:不同于MatchParent美侦,MatchConstraints受控件約束影響。
MatchConstraints效果 -
WrapContent
WrapContent
WrapContent效果:
WrapContent效果
基本的ConstraintLayout用法到此就結(jié)束了魂奥,我們應(yīng)該已經(jīng)可以通過此方法處理一些簡單的頁面布局應(yīng)用了菠剩。