我有一个非常常见的用例:屏幕上有多行信息。我希望实现这些视图而不必使用嵌套的视图组。每行应有一个最小高度,但如果内容大于最小高度,则展开。内容应该垂直嵌套。
看起来这个简化的例子应该可以:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/view"
app:layout_constraintBottom_toBottomOf="@+id/view"/>
<View
android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#8800ff00"
app:layout_constraintHeight_min="100dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="@id/textView"/>
</android.support.constraint.ConstraintLayout>
我没有为每一行创建一个视图组,而是使用带有约束的平面布局。每行的视图设置行高,可以单击。行中的视图是布局层次结构中的兄弟姐妹,但在该视图的视图中间垂直居中。因为我已经指定了
app:layout_constraintHeight_min
并将视图的底部锚定到内容的底部,它应该随着内容的增长而增长。
但有一个问题:
ConstraintLayout在行上方添加了不需要的间距!请注意,行上方不需要的间距等于内容底部和行底部之间的正确间距。
我的理论是这样的:由于视图的底部被锚定在内容的底部(文本视图),它希望紧紧地固定在它旁边。如果我强迫它移动得更远,它会添加一个类似于底部边距的东西来实现这一点,它会添加一个类似的顶部边距来实现对称。
我怎样才能让它停止?如果不是因为顶部不必要的间距,我会得到我所需要的。也许有一些特殊的约束技巧,一些神奇的属性来修复这种行为。或者可能有一种完全不同的方式使用ConstraintLayout来实现我想要的UI。
我意识到使用固定高度的行会使这变得更简单,但如果内容可以增长,我不喜欢这样做。
我可以改变我的UI,让每一行都有一个嵌套的ConstraintLayout,但我不想这样做,因为我已经努力使复杂的布局完全平坦,没有多层视图组。但如果我找不到更好的解决方案,我会这么做,我希望在这里找到。