我在 ConstraintLayout 中按顺序水平组织了一个 TextView 和一个 Button:
我需要第一个元素 (TextView) 在文本足够短时只占用必要的空间,但在需要显示更多文本时根据需要展开,同时仍然为第二个元素 (Button) 留出足够的空间完全呈现在 View 内,其末端与父 View 的末端对齐。
这是 XML 当前的样子:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
<TextView
android:id="@+id/element1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Short enough text"/>
<Button
android:id="@+id/element2"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_gravity="center_vertical"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="@drawable/element2ButtonDrawable"
android:drawablePadding="0dp"
android:drawableStart="@drawable/element2ButtonDrawable"
android:text="Action"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="@id/element1"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.0"/>
</android.support.constraint.ConstraintLayout>
这是当从“足够短的文本”切换到“较长的文本会导致大部分底部被推到父 View 边界之外”时树的呈现方式:
是否可以通过使用 ConstraintLayout 来实现我想要做的事情?
(在撰写本文时,最新版本为 1.0.2)
谢谢!
最佳答案
您应该使用打包的水平链,您的 TextView 的宽度与约束匹配且水平偏差等于 0.0
解决方法:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:text="Short enough text"
app:layout_constraintWidth_default="wrap"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintHorizontal_bias="0.0" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:drawablePadding="0dp"
android:drawableStart="@drawable/element2buttondrawable"
android:text="Action"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@+id/textView"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</android.support.constraint.ConstraintLayout>
以下是此布局在具有不同文本和方向的设备上的外观:
您可以在以下帖子中阅读有关使用链的更多信息:
关于android - ConstraintLayout - 让元素占用必要的空间直到可用空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42914591/