Android Studio中如何分离AdView与NestedScrollView并避免重叠?
解决AdView与NestedScrollView重叠问题
问题出在你的NestedScrollView设置了layout_height="match_parent",且未与底部的AdView建立约束关系,导致它会占满整个父布局空间,和底部的AdView发生重叠。只需通过ConstraintLayout的约束调整即可解决,具体修改如下:
关键修改点:
- 将
NestedScrollView的高度改为0dp(即match_constraint),让它根据约束自动计算高度 - 给
NestedScrollView添加底部约束,使其底部对齐AdView的顶部 - 移除
AdView中属于RelativeLayout的冗余属性(ConstraintLayout下无效)
修改后的完整代码:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/grey" tools:context=".MainActivity"> <androidx.core.widget.NestedScrollView android:id="@+id/ScrollView" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toTopOf="@id/adView"> <!-- 这里放置你的滚动内容 --> </androidx.core.widget.NestedScrollView> <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto" android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" ads:adSize="BANNER" ads:adUnitId="ca-app-pub-3940256099942544/6300978111" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"> </com.google.android.gms.ads.AdView> </androidx.constraintlayout.widget.ConstraintLayout>
说明:
修改后,NestedScrollView会填充从父布局顶部到AdView顶部的所有空间,AdView固定在父布局底部,两者不会再重叠,NestedScrollView的底部内容也能正常滚动显示,不会被AdView遮挡。
内容的提问来源于stack exchange,提问作者Marfog509
相关产品推荐
相关产品推荐

