话不多说,直接上代码:
<?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"
补充:
1、对于上述场景,如果是动态去设置 TextView 的内容,且宽度随内容的而变化,且满足
app:layout_constraintWidth_max="wrap"
app:layout_constraintWidth_percent="0.1"
即最大宽度为父布局的 0.1,则在动态设置内容之后,需要调用 TextView#requestLayout()
,来使得布局在因内容长度变化导致宽度变化之后刷新布局。
如果没有 requestLayout()
,则当对 TextView 设置了很长的内容导致其宽度变宽之后(假设变宽之后为 W),再设置较短内容时,宽度还是会维持为 W,不会实时的因为内容变短而变短。
2、如果子 View 是自定义的,则需要处理这种 wrap 情况,因为我们设置的子 view 的 android:layout_width
为 0