在 ConstraintLayout 中使用 match_parent

Using match_parent in ConstraintLayout

当我们不需要任何 "constrainting" 时,如果我们在 ConstraintLayout 中使用 match_parent 可以吗?

例如:

<View
    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_toRightOf="parent"/>

可以简化为:

<View
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

它违背了约束的目的,如果您要使用第二种方法,您可能应该使用 LinearLayout 或 RelativeLayout。 ConstraintLayout 的目标是最小化 XML 内布局的子级别/子嵌套(none 的多个 LinearLayouts 或 RelativeLayouts,我们可以使用 Groups 或 ConstraintLayout Flow)

这完全没问题,如果 match_parent 给您相同的结果,那么使用约束通常是更好的主意,您应该这样做,因为它不会那么混乱。但最终这只是个人喜好,并没有那么重要。

阅读Build a Responsive UI

The best way to create a responsive layout for different screen sizes is to use ConstraintLayout as the base layout in your UI. ConstraintLayout allows you to specify the position and size for each view according to spatial relationships with other views in the layout. This way, all the views can move and stretch together as the screen size changes.

两种布局都是正确的。每种布局都有其自身的优点,但是当涉及到复杂的、动态的和响应式视图时,您应该始终选择 Constraint Layout.

<View
    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_toRightOf="parent"/>

    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"

    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"