Update
我想提一下,Remq 的答案有效,并且解决了我在下面提到的自引用问题,其中视图的宽度由使用相同视图作为引用 id 的屏障的位置决定。关键似乎是规范app:layout_constraintWidth_min="wrap"
对于这两种观点。我不清楚为什么这会起作用,或者它会继续起作用,但我想记下它
更新#2
我又看了一遍为什么 Remq 的答案有效。我的经验是,如果不指定app:layout_constraintWidth_min="wrap"
对于视图,两个视图都折叠为零宽度。一旦视图的宽度为零,app:layout_constraintWidth_min="wrap"
再次生长它们,以便包裹内容物。这只是我的猜测,没有证据证明这是正在发生的事情,但这是有道理的。
我在 Stack Overflow 上多次看到类似的问题。在我看来,这些问题从来没有一个令人满意的答案(包括我已经回答过的问题)。困难在于存在依赖性问题,因为一个视图依赖于另一个视图的宽度,而另一个视图依赖于第一个视图的宽度。我们陷入了参照困境。 (以编程方式强制宽度始终是一种选择,但似乎不可取。)
另一种可能更好的方法是使用自定义约束助手这将检查引用视图的大小并将所有视图的宽度调整为最大的宽度。
习俗约束助手放置在布局的 XML 中并引用受影响的视图,如以下示例布局所示:
活动主线
<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>
习俗约束助手看起来像这样:
最大宽度助手
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
}
}
}
}
}
}
布局显示如下所示。