我正在尝试在 constraintlayout 中使用两个 View 。但是一旦分配了边距, subview 就会出现未定义的行为。我们将不胜感激。
这是我的代码:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:src="@drawable/ic_action_google_play"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/txtNew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="TextHere"
android:textSize="24sp"
app:layout_constraintLeft_toRightOf="@+id/img"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
最佳答案
在 ConstraintLayout 中,要在任何一侧(左、上、右、下)应用边距,必须显式定义该侧的约束。如果您的情况是,您希望 ImageView 的每一侧都有“16dp”边距,因此您需要为该 ImageView 的每一侧声明约束。您用 XML 编写了以下内容:
<ImageView
android:layout_margin="16dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
像这样替换:
<ImageView
android:id="@+id/img"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="16dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="16dp"
/>
要使 Right 和 Bottom 的边距起作用,您还需要添加以下内容:
app:layout_constraintRight_toLeftOf="@+id/txtNew"
android:layout_marginRight="16dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="16dp"
同样的事情也适用于 TextView。
关于android - 约束布局的子边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49473386/