【发布时间】:2018-07-13 23:42:22
【问题描述】:
我的最终目标是在左对齐、打包的水平链中拥有两个单行 TextView,使它们都可以增长以填充剩余空间,必要时将其均匀分割,在没有空间时省略。
这是我尝试完成的布局代码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
tools:text="@tools:sample/lorem"
app:layout_constrainedWidth="true"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="@id/textView2"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintHorizontal_bias="0"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:ellipsize="end"
android:maxLines="1"
tools:text="@tools:sample/lorem"
app:layout_constrainedWidth="true"
app:layout_constraintStart_toEndOf="@id/textView1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</android.support.constraint.ConstraintLayout>
如您所见,我在水平链中布置了两个文本视图。我已经将链条样式设置为打包,以便它们保持在一起。我已将水平偏差设置为 0,以便链左对齐。我将宽度设置为 wrap_content 以便它们在文本很短时不会拉伸,并且我还设置了 app:layout_constrainedWidth="true" 以便它们在文本很长时不会超出范围。当 textView2 中的文本增长时,这 几乎 完全符合我的要求 except。随着 textView1 的增长,它会将 textView2 向右推,直到达到其约束,此时它会椭圆化(如预期/期望的那样),但对于 textview2,情况并非如此。随着 textView2 的增长,它会拉伸以填充右侧的房间,但一旦达到其约束,而不是椭圆化,它会继续拉伸并开始将 textView1 推向左侧,直到它不再可见。
视觉辅助(实际行为):
我尝试在每个视图上使用诸如将 layout_constraintHorizontal_weight 设置为 .5 之类的东西,但除非我将两个视图宽度都更改为 0dp (match_constraints),否则这将没有效果,这打破了两个视图都有短文本的情况(它添加两个文本视图之间的额外空间)。
感觉是,当您将width=wrap_content 与layout_constrainedWidth=true 结合使用时,权重值会被忽略。这只是 ConstraintLayout 的限制吗?我花了很多时间试图找出一种方法来完成这项工作,但现在似乎不可能。我已经退回到使用 LinearLayout 并做出一些设计妥协,但如果有人有任何想法,我真的很想让它工作。谢谢!
【问题讨论】:
-
你有没有试过在左视图设置
app:layout_constraintWidth_min="someVal"来防止它缩小到0? -
那个我没试过。听起来它可以帮助视图完全消失,但它仍然不能让我得到我想要的,因为我使用的字符串可能比我的最小值短,这会导致空白,从技术上讲,我可以使用最小宽度第一个视图中的空字符串为 0。感谢您的建议,在此期间我也许可以使用它
-
您接受代码中的解决方案吗?
-
@deadfish 取决于...如果它只是在代码中初始化无法在 xml 中完成的东西,那么可以,但是测量文本并相应调整布局的东西会破坏这个目的问题,因为我特别试图使用 ConstraintLayout 属性使其“自然”工作,此时我可以制作自定义视图或真正使用任何类型的视图
标签: android android-layout android-support-library android-constraintlayout