从RelativeLayout迁移至ConstraintLayout:如何将AdView置于底部且位于其他内容下方?
从RelativeLayout迁移到ConstraintLayout:底部AdView布局实现
嘿,这个迁移问题我熟!之前刚帮朋友搞定过类似的,其实ConstraintLayout实现起来也很直观,我给你一步步拆解:
首先先回顾下你原来的RelativeLayout实现代码(应该和这个差不多吧):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 承载其他内容的容器 --> <LinearLayout android:id="@+id/contentContainer" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/adView" android:orientation="vertical"> <!-- 这里是你的业务内容 --> </LinearLayout> <!-- AdMob 广告View --> <com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="#eee"/> </RelativeLayout>
接下来是转换成ConstraintLayout的等效实现,核心就是用约束关系替代RelativeLayout的位置属性:
<androidx.constraintlayout.widget.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"> <!-- 承载其他内容的容器 --> <LinearLayout android:id="@+id/contentContainer" android:layout_width="match_parent" android:layout_height="0dp" <!-- 关键:用0dp让容器根据约束自动填充空间 --> android:orientation="vertical" <!-- 对应原来的layout_above:把容器底部贴在AdView顶部 --> app:layout_constraintBottom_toTopOf="@+id/adView" <!-- 让容器顶部对齐父布局顶部 --> app:layout_constraintTop_toTopOf="parent" <!-- 左右对齐父布局,保证宽度铺满 --> app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"> <!-- 这里是你的业务内容 --> </LinearLayout> <!-- AdMob 广告View --> <com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#eee" <!-- 对应原来的layout_alignParentBottom:把AdView底部贴在父布局底部 --> app:layout_constraintBottom_toBottomOf="parent" <!-- 左右对齐父布局,保证宽度铺满 --> app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
关键属性对应解释:
对于AdView:
app:layout_constraintBottom_toBottomOf="parent"完全等效于原来的android:layout_alignParentBottom="true",把广告View牢牢固定在布局底部- 加上
constraintStart_toStartOf和constraintEnd_toEndOf是为了让AdView的左右边缘和父布局对齐,配合match_parent的宽度属性生效
对于内容容器:
- 高度设为
0dp是ConstraintLayout的特殊用法(叫"match constraints"),意思是让容器根据上下左右的约束自动计算高度,这样就能自动填满AdView上方的所有剩余空间 app:layout_constraintBottom_toTopOf="@+id/adView"对应原来的android:layout_above="@+id/adView",直接把容器底部和AdView顶部绑定,实现内容在广告上方的效果
- 高度设为
如果之后你遇到AdView动态隐藏的场景(比如无广告时),还可以给内容容器加一个备用的底部约束app:layout_constraintBottom_toBottomOf="parent",再通过app:layout_constraintPriority设置优先级,不过基础场景用上面的代码就完全够用啦!
内容的提问来源于stack exchange,提问作者NullPointerException
相关产品推荐
相关产品推荐

