感谢@cheticamp 和他在此处提供的答案,实现所需行为的最佳方法是编写一个简单的方法ConstraintHelper
,将所有孩子的宽度设置为最大。
class MaxWidthConstraint @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintHelper(context, attrs, defStyleAttr) {
override fun updatePostMeasure(container: ConstraintLayout) {
val maxWidth =
referencedIds.asSequence().map { container.getViewById(it) }
.map { container.getViewWidget(it) }
.map { it.width }
.max() ?: 0
referencedIds.asSequence().map { container.getViewById(it) }
.map { container.getViewWidget(it) }
.forEach { it.width = maxWidth }
}
}
所以布局代码将是:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="HardcodedText">
<Button
android:id="@+id/btn_25"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="25%"
android:textAlignment="center"
app:layout_constraintEnd_toStartOf="@id/btn_50"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_50"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50%"
app:layout_constraintEnd_toStartOf="@id/btn_75"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintStart_toEndOf="@id/btn_25"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_75"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="75%"
app:layout_constraintEnd_toStartOf="@id/btn_100"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintStart_toEndOf="@id/btn_50"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_100"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100%"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintStart_toEndOf="@id/btn_75"
app:layout_constraintTop_toTopOf="parent" />
<com.myapplication.widgets.MaxWidthConstraint
android:layout_width="0dp"
android:layout_height="0dp"
app:constraint_referenced_ids="btn_25,btn_50,btn_75,btn_100"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>