話不多說,直接上代碼:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:background="@color/colorPrimary"
app:layout_constraintWidth_max="wrap"
app:layout_constraintWidth_percent="0.1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Hello World Hello World Hello World Hello World"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
關鍵就是:
app:layout_constraintWidth_max="wrap" <!-- 設置爲 wrap -->
app:layout_constraintWidth_percent="0.1" <!-- 設置爲想要的比例 -->
android:layout_width="0dp" <!-- 注意是 0dp -->
但是有一點需要注意,如果此時 view 沒有填充內容,比如 TextView
沒有 text,此時其 width 就會被直接設置 percent 對應的寬度。 比如上述示例代碼,TextView
的 text 設置爲 ""
空字符串,或者 null,其 width 就會被設置爲 ConstraintLayout
width 的 0.1
。
下面 percent="0.1"
下面 percent="0.5"