【发布时间】:2019-11-14 18:48:00
【问题描述】:
【问题讨论】:
标签: android android-layout android-constraintlayout
【问题讨论】:
标签: android android-layout android-constraintlayout
Barriers 将为您施展魔法!
使用此功能,您可以自动获取特定范围内最宽对象的宽度。
来自 Android 文档:
Barrier 引用多个小部件作为输入,并根据指定一侧的最极端小部件创建虚拟指南。例如,左屏障将与所有引用视图的左侧对齐。
以下 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>
【讨论】: