答案 0 :(得分:7)
Barriers将为您做魔术!
使用此功能,您可以自动获得特定范围内最宽对象的宽度。
从Android Documentaion:
屏障会引用多个窗口小部件作为输入,并根据指定侧最极端的窗口小部件创建虚拟准则。例如,左障碍将与所有参考视图的左侧对齐。
以下xml将检查视图content_text
和bottom_text
的最宽宽度
<androidx.constraintlayout.widget.Barrier
android:id="@+id/barrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="end"
app:constraint_referenced_ids="content_text,bottom_text" />
现在,您可以将此障碍用作其他任何视图的约束(在同一ConstraintLayout内部)
<View
android:id="@+id/card_background"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@color/colorPrimary"
app:layout_constraintBottom_toBottomOf="@id/content_text"
app:layout_constraintEnd_toEndOf="@id/barrier"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@id/content_text" />
这就是我的结果:
我完整的XML:
<?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"
android:layout_margin="16dp"
tools:context=".MainActivity">
<View
android:id="@+id/card_background"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@color/colorPrimary"
app:layout_constraintBottom_toBottomOf="@id/content_text"
app:layout_constraintEnd_toEndOf="@id/barrier"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@id/content_text" />
<TextView
android:id="@+id/content_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:text="This is a very large content text. It is so long that it needs a second line"
android:textColor="@android:color/black"
android:textSize="22sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/bottom_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a bottom text with a particular length"
android:textColor="@android:color/black"
android:textSize="14sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/card_background" />
<!-- Magic happens here -->
<androidx.constraintlayout.widget.Barrier
android:id="@+id/barrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="end"
app:constraint_referenced_ids="content_text,bottom_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
希望这会有所帮助。
Here could you read more about barriers