現在都以這種佈局為主
大概可以完成80%以上的畫面了吧
(原則上不使用 match_parent 而改用 0dp 也就是所謂的 match constraints)
基本用法
先來個xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/tv_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/tv_2"
/>
<TextView
android:id="@+id/tv_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_1"
app:layout_constraintBottom_toBottomOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
效果圖如下
在xml開頭的地方,加了下列這行之後
才能使用下列這種排列方式
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layout_constraintStart_toStartOf="parent"
共有以下八種
app:layout_constraintStart_toStartOf="" << 自己的左邊與別人的左邊貼在一起
app:layout_constraintStart_toEndOf="" << 自己的左邊與別人的右邊貼在一起
app:layout_constraintEnd_toEndOf="" << 自己的右邊與別人的右邊貼在一起
app:layout_constraintEnd_toStartOf="" << 自己的右邊與別人的左邊貼在一起
app:layout_constraintTop_toTopOf="" << 自己的上面與別人的上面貼在一起
app:layout_constraintTop_toBottomOf="" << 自己的上面與別人的下面貼在一起
app:layout_constraintBottom_toBottomOf="" << 自己的下面與別人的下面貼在一起
app:layout_constraintBottom_toTopOf="" << 自己的下面與別人的上面貼在一起
雙引號裡面,可以放
"parent" << 父視窗
"@+id/tv_2" << 同頁裡定義的其他物件的 id
進階用法 - Guideline
如果要從畫面中間開始對齊可以使用這個方法
基本 xml 如下
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="100dp" />
效果圖如下
可以使用的定位方法如下所列(只能選擇一種)
app:layout_constraintGuide_begin="100dp" << 從左邊算來 100dp 的距離
app:layout_constraintGuide_end="100dp" << 從右邊算來 100dp 的距離
app:layout_constraintGuide_percent="0.4" << 從左邊算來 百分之40 的距離
也可以將垂直改為水平方式
(begin會改從上面算起,end改從底下算起,percent改為從上面算起)
android:orientation="horizontal"
進階用法 - chainStyle
一行有多個物件排列在一起的話,可以使用這個方法,讓它以不同的方式排列
xml 用法如下
app:layout_constraintVertical_chainStyle="" << 垂直排列方式
app:layout_constraintHorizontal_chainStyle="" << 水平排列方式
雙引號裡面,可以放以下的 1、2、4
1. "spread"
2. "spread_inside"
3. "weighted"
4. "packed"
相對應的效果圖如下
沒有留言:
張貼留言