首先,我想谈谈两个独特的行为ConstraintLayout
当你第一次拿起它时,这并不一定很明显。
match_parent
不支持
这一细节隐藏在开发者指南的一行文字中:https://developer.android.com/training/constraint-layout/index.html https://developer.android.com/training/constraint-layout/index.html
Note: 不能使用match_parent
对于 a 中的任何视图ConstraintLayout
。而是使用“匹配约束”(0dp
).
要获得“匹配父级”行为,请结合0dp
视图两个相应边缘的约束尺寸:
android:layout_width="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
仅当边距具有相应的约束时才会强制执行
只需添加android:layout_marginTop
除非该视图也有顶部约束,否则不会执行任何操作,例如app:layout_constraintTop_toTopOf
or app:layout_constraintTop_toBottomOf
.
您的具体问题
这是更新后的布局:
<?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"
android:background="@android:color/transparent">
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="5dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="@+id/adView"/>
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:adSize="BANNER"
app:adUnitId="@string/ad_id_banner"/>
</android.support.constraint.ConstraintLayout>
实现水平居中AdView
,我们将左右边缘约束为父级的左右边缘。这个“拉”AdView
每一侧均等,居中。为了让它粘在屏幕底部,我们将其底部边缘限制在父级的底部。
至于LinearLayout
,首先我们将其尺寸更改为0dp
。这将使约束定义其大小。然后我们将顶部、左侧和右侧边缘约束到父级的顶部、左侧和右侧边缘。我们将底部边缘约束到顶部边缘AdView
。这会导致它水平填充屏幕,并填充所有垂直空间AdView
没有使用。
最后,我们更改上边距AdView
到底部边距LinearLayout
。这是因为LinearLayout
的底边被限制在AdView
的上边缘(但AdView
的顶部边缘不限于LinearLayout
的底部边缘,因此顶部边缘不会产生任何影响)。