我在使用 ConstraintLayout 时遇到了使用 <include>
和 <merge>
标签的困难。
我想创建一个扁平的视图层次结构(因此使用 Constraints),但仍然希望元素可重用。因此,我在我的布局中使用了 <include>
,并在包含的布局中使用了 <merge>
,以避免嵌套布局(尤其是避免嵌套 ConstraintLayouts)。
所以我写了这个:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/review_1"
layout="@layout/view_movie_note"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/review_2"/>
<include
layout="@layout/view_movie_note"
android:id="@+id/review_2"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginLeft="7dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="@+id/review_1"
app:layout_constraintRight_toRightOf="parent"
/>
</android.support.constraint.ConstraintLayout>
并且这个视图电影注释:
<merge>
<TextView
android:id="@+id/note_origin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginStart="5dp"
app:layout_constraintStart_toStartOf="@+id/cardView2"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginLeft="5dp" />
<android.support.v7.widget.CardView
android:id="@+id/five_star_view_container"
android:layout_width="0dp"
android:layout_height="52dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="10dp"
android:elevation="3dp"
app:cardUseCompatPadding="true"
app:contentPaddingTop="22dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_min="52dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/note_origin">
<FiveStarsView
android:id="@+id/five_star_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="@+id/cardView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:cardBackgroundColor="@color/colorPrimary"
app:contentPaddingLeft="15dp"
app:contentPaddingRight="15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/note_origin">
<TextView
android:id="@+id/grade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp" />
</android.support.v7.widget.CardView>
</merge>
我期望得到这个:
但实际上我得到了这个:
很明显,我在<include>
标签中设置的约束被包含布局中的约束覆盖了。
这是否是预期行为?如果是,我们应该如何使用<include>
和ConstraintLayout保持平面布局呢?