一、介紹
ConstrainLayout是Android Studio 2.3之後新增的布局組件,它是基於ConstraintLayout演算法庫實現的,旨在提供更靈活、更高效的布局方式。它能夠快速創建複雜的布局,以解決在早期的開發過程中遇到的難點。
二、使用
1、基本概念
ConstrainLayout布局中有好幾個重要的概念需要理解。
- Constraint:表示一個對象應該相對於其他對象的位置。
- Anchor:Constraint連接到視圖的一端,通常是邊緣。需要在布局中定義錨點,以便ConstrainLayout可以找到這些錨點。
- Horizontal Bias/Vertical Bias:可以沿水平和/或垂直軸調整視圖的位置。
- Gone Margin:當視圖是gone時,Gone Margin指定該視圖的空間大小,而不是視圖的實際大小。這有助於避免因消失而導致的裂縫或布局問題。
2、創建布局
創建一個ConstrainLayout布局很簡單,只需按照下面的示例中進行代碼編寫即可。
<?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=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BUTTON"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
在這個布局中,我們創建了一個Button,並將它放在布局的中心。這是通過將Button的每個邊緣的Constraint(即上下左右的約束)設置為其父控制項的相應邊緣,使Button在布局中居中。
3、約束
為了讓視圖相對於其他視圖定位,我們需要使用constraint來指定約束關係。下面是一些常用的約束規則。
- app:layout_constraintLeft_toRightOf:指定視圖的左邊緣相對於目標視圖的右邊緣的約束關係。
- app:layout_constraintStart_toEndOf:指定視圖的起始端與目標視圖的結束端相對的約束關係。
- app:layout_constraintTop_toBottomOf:指定視圖的頂部與目標視圖的底部對齊的約束關係。
- app:layout_constraintEnd_toStartOf:指定視圖的結束端與目標視圖的起始端相對的約束關係。
- app:layout_constraintBottom_toTopOf:指定視圖的底部與目標視圖的頂部對齊的約束關係。
- app:layout_constraintVertical_bias:指定視圖在垂直方向上相對於目標視圖的偏移,值從0到1。
- app:layout_constraintHorizontal_bias:指定視圖在水平方向上相對於目標視圖的偏移,值從0到1。
4、刪除約束
要在ConstrainLayout布局中刪除約束,請在視圖的約束屬性中手動刪除相應的約束。或者,選擇一個視圖並右鍵單擊它以打開「約束」屬性菜單。這裡可以刪除指定方向的約束關係。
5、Gone時的計算方式
視圖消失時,需要清除與該視圖相關的約束。這樣才能避免有「空隙」在布局中。同樣,當一個視圖是gone時,Gone Margin可以指定該視圖的空間大小,而不是視圖的實際大小。
三、優點
1、性能優秀
在大多數情況下,使用ConstrainLayout的布局比其他布局組件快。相對於LinearLayout和RelativeLayout來說,ConstrainLayout性能出類拔萃,特別是在複雜布局的情況下。
2、布局靈活
ConstrainLayout允許根據個人需求創建布局。一個對象可以連接到另一個對象之上,在應用後其位置將被偏移。此外,ConstrainLayout提供了水平和垂直方向上的偏移支持。
3、支持鏈式約束
當一系列的視圖需要一起移動時,使用鏈式約束支持始終是最好的選擇,因為它比設置多個獨立的約束更簡單、更有效。
四、結論
ConstrainLayout是一種高效、強大、靈活的布局方式,它可以快速創建複雜的布局。它使用起來很簡單,只需要一些基本的理解就能在應用程序中使用它。因此,ConstrainLayout在Android開發中具有極高的實際價值,並且應該成為每個Android開發者工具箱中必不可少的一部分。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/185045.html