当在 ConstraintLayout 中使用时,我无法理解边距 (android:layout_margin*
) 的行为。边距似乎只在某些情况下生效,我希望有人能给我解释一下(或者确认这是一个 ConstraintLayout 错误)。
我有以下布局...
<?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">
<View
android:id="@+id/leftView"
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_marginEnd="20dp"
android:background="@android:color/holo_blue_dark"
app:layout_constraintEnd_toStartOf="@+id/rightView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<View
android:id="@+id/rightView"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@android:color/holo_green_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
...产生以下输出...
但是,当我将边距从 leftView
更改为 rightView
时...
<?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">
<View
android:id="@+id/leftView"
android:layout_width="0dp"
android:layout_height="100dp"
android:background="@android:color/holo_blue_dark"
app:layout_constraintEnd_toStartOf="@+id/rightView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<View
android:id="@+id/rightView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginStart="20dp"
android:background="@android:color/holo_green_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
...边距意外消失...
有人可以解释这是否是预期的行为,如果是,为什么会这样?
最佳答案
因为 leftview
取决于rightview
, 所以你可以设置 leftview
的边距至 rightview
.
当 View 有边距时,这意味着 View 正在为 View 所依赖的空间 提供空间。
如果你写android:layout_marginStart="20dp"
在rightview
, 它不会给 leftview
留出空间因为rightview
不依赖到leftview
.
关于android - ConstraintLayout 中的边距行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46438204/