Android里的ConstraintLayout是個(gè)非常強(qiáng)大的工具,它有效的解決了Android里L(fēng)ayout的層級(jí)嵌套的問題博投。使用一個(gè)ConstraintLayout可以實(shí)現(xiàn)之前多個(gè)Layout才能實(shí)現(xiàn)的效果绸贡。
本篇文章就介紹下ConstraintLayout里比較進(jìn)階用法之一:Guideline。
Guideline介紹
Guideline是一種特殊的控件,它在界面上是看不見的(被標(biāo)記為View.Gone)听怕,只是用來做參考線捧挺。它一般有水平和垂直兩種。
Guideline的定位有兩種方法:
1.絕對(duì)定位:使用layout_constraintGuide_begin
和layout_constraintGuide_end
2.百分比定位:使用layout_constraintGuide_percent
下面以兩個(gè)實(shí)例來說明Guideline的用法尿瞭。
使用Guideline實(shí)現(xiàn)控件對(duì)稱布局
假如闽烙,我們想要實(shí)現(xiàn)如下的效果,控件A和控件B声搁,在屏幕上對(duì)稱顯示黑竞。
如果不用ConstraintLayout,至少要嵌套兩級(jí)的Layout才能實(shí)現(xiàn)酥艳。而用ConstraintLayout里的Guideline摊溶,可以很容易的實(shí)現(xiàn)這種效果爬骤。
在這個(gè)例子里充石,我們可以先定義一個(gè)垂直的Guideline,然后用這行代碼layout_constraintGuide_percent="0.5"
讓Guideline垂直居中:
<android.support.constraint.Guideline
android:id="@+id/guide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5"/>
然后以這根Guideline為基準(zhǔn)霞玄,左右各constraint一個(gè)控件骤铃,注意這兩行代碼app:layout_constraintRight_toLeftOf="@id/guide"
和app:layout_constraintLeft_toRightOf="@id/guide"
:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="確定"
app:layout_constraintRight_toLeftOf="@id/guide"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="200dp"
android:layout_marginRight="50dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取消"
app:layout_constraintLeft_toRightOf="@id/guide"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="200dp"
android:layout_marginLeft="50dp"/>
效果如下圖,在App真正運(yùn)行的時(shí)候坷剧,中間那根線是看不見的惰爬。
使用Guideline實(shí)現(xiàn)按百分比定位控件
假如我們要在屏幕上顯示一行字,這行字距離屏幕上邊緣200dp惫企。這個(gè)效果雖然很容易實(shí)現(xiàn)撕瞧,但是,因?yàn)楝F(xiàn)實(shí)中安卓手機(jī)的屏幕分辨率的差異狞尔,不同的手機(jī)上顯示的效果可能會(huì)不同丛版。比如,在屏幕比較長的手機(jī)上偏序,感覺下面會(huì)比較空页畦。如下圖:
使用Guideline可以解決這個(gè)問題研儒,因?yàn)镚uideline支持百分比的定位豫缨。
首先,新建一個(gè)水平Guideline端朵,設(shè)置為距離上邊緣30%:
app:layout_constraintGuide_percent="0.3"
:
<android.support.constraint.Guideline
android:id="@+id/guide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.3" />
然后控件根據(jù)這個(gè)Guideline來定位好芭,注意這句app:layout_constraintTop_toBottomOf="@id/guide"
:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這行文字距離上邊緣30%"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/guide"
android:textSize="30sp"/>
最終的效果是這樣的:
因?yàn)槭褂昧税俜直葋矶ㄎ唬阅芨玫倪m配不同分辨率冲呢。