ConstraintLayout(約束佈局)之初學

一、作用

解決多層嵌套佈局影響性能的問題。

二、用法

1.相對定位

如上圖佈局,在約束佈局中,其中中間Home的id爲message,垂直和水平方向都是居中,佈局如下:

<TextView
    android:id="@+id/message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/title_home"
    android:background="@color/colorPrimary"
    android:textColor="#fff"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"/>

重點就在最後四條,按照字面意思理解四句話分別是:

message的左邊約束到父級的左邊;

message的上邊約束到父級的上邊;

message的右邊約束到父級的右邊;

message的下邊約束到父級的下邊。

這裏的“約束到”,有點對齊的意思。同時具有這四個屬性才能使其在屏幕中心位置。

其餘四個TextView分別爲tv1, tv2, tv3, tv4,挑幾個簡單的記錄:

① text1的實現:參照相對佈局的方式,應該是使用類似於toRightOf的屬性。但是寫上以後發現TextView報紅提示:

This view is not constrained vertically: at runtime it will jump to the top unless you add a vertical constraint.

大概意思是說這個view沒有在垂直方向上沒有被約束,如果不加上垂直方向上的約束在運行時這個view會跳到頂部。

那麼參照message的寫法,加上

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toRightOf="@id/message"
    android:text="我是text1"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"/>

即把tv1的左邊約束到message的右邊,同時實現垂直方向上的居中,這樣就實現了和message保持同一水平線。

也有另一種寫法也能實現相同效果:

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toRightOf="@id/message"
    android:text="我是text1"
    app:layout_constraintBaseline_toBaselineOf="@id/message"/>

這裏的Baseline指的是文本基線,toBaselineOf可以使兩個控件文本垂直方向上對齊,相當於對齊兩者的下劃線。

②tv2的實現:同樣地通過約束相對位置來實現:

<TextView
    android:id="@+id/tv2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="我是text2"
    app:layout_constraintTop_toBottomOf="@+id/message"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>

還是要注意,必須同時在水平和垂直方向上對控件進行約束。

其他兩個實現方式相同,就不再贅述。

2.角度定位

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章