更新
我想提一下,Remq 的答案有效并解决了我在下面提到的自我引用问题,其中视图的宽度由使用与引用 id 相同的视图的屏障的位置确定。关键似乎是两个视图的 app:layout_constraintWidth_min="wrap" 规范。我不清楚为什么这会起作用,或者它会继续起作用,但我想记下它
更新 #2
我又看看为什么 Remq 的答案有效。我的经验是,如果没有为视图指定app:layout_constraintWidth_min="wrap",两个视图都会折叠到零宽度。一旦视图的宽度为零,app:layout_constraintWidth_min="wrap" 就会再次增长它们,以便包装内容。这只是我的猜测,没有证据证明这是正在发生的事情,但这是有道理的。
我曾多次在 Stack Overflow 上看到过类似的问题。这些问题从来没有一个令人满意的答案IMO(包括我已经回答的问题。)困难在于存在依赖性问题,因为一个视图取决于另一个视图的宽度,而另一个视图取决于第一个视图的宽度。我们陷入了参照的困境。 (以编程方式强制宽度始终是一种选择,但似乎不可取。)
另一种可能更好的方法是使用自定义 ConstraintHelper,它将检查引用视图的大小并将所有视图的宽度调整为最大宽度。
自定义 ConstraintHelper 放置在布局的 XML 中,并引用受影响的视图,如以下示例布局所示:
activity_main
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Button1"
app:layout_constraintBottom_toTopOf="@+id/button2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Button2 may be larger"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/button1" />
<com.example.constraintlayoutlayer.GreatestWidthHelper
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:constraint_referenced_ids="button1,button2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
自定义的ConstraintHelper如下所示:
GreatestWidthHelper
class GreatestWidthHelper @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintHelper(context, attrs, defStyleAttr) {
override fun updatePostMeasure(container: ConstraintLayout) {
var maxWidth = 0
// Find the greatest width of the referenced widgets.
for (i in 0 until this.mCount) {
val id = this.mIds[i]
val child = container.getViewById(id)
val widget = container.getViewWidget(child)
if (widget.width > maxWidth) {
maxWidth = widget.width
}
}
// Set the width of all referenced view to the width of the view with the greatest width.
for (i in 0 until this.mCount) {
val id = this.mIds[i]
val child = container.getViewById(id)
val widget = container.getViewWidget(child)
if (widget.width != maxWidth) {
widget.width = maxWidth
// Fix the gravity.
if (child is TextView && child.gravity != Gravity.NO_GRAVITY) {
// Just toggle the gravity to make it right.
child.gravity = child.gravity.let { gravity ->
child.gravity = Gravity.NO_GRAVITY
gravity
}
}
}
}
}
}
布局显示如下。