You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Ad Banner加载报错:调用loadAd前需设置广告尺寸与ID

问题详情

我已尝试过类似问题的解决方案,但均无效。

我的Google Ad Banner XML代码如下:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/konstraitLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:padding="0dp"
app:layoutDescription="@xml/activity_main_scene"
tools:context=".MainActivity">

    ...

    <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" />

    ...

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity中的代码:

adView = findViewById(R.id.adView);

AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);

调用loadAd时出现如下错误:

The ad size and ad unit ID must be set before loadAd is called

解决方法

  • 修复命名空间重复问题
    布局中重复声明了xmlns:ads(根布局和AdView都有声明),这会导致属性解析异常。修改根布局,只保留一次必要的命名空间声明:

    <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:id="@+id/konstraitLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFF"
        android:padding="0dp"
        app:layoutDescription="@xml/activity_main_scene"
        tools:context=".MainActivity">
    

    AdView部分可直接使用app命名空间配置广告属性,若要保留ads命名空间,仅在根布局声明一次即可。

  • 代码中手动配置广告属性
    如果XML属性解析仍有问题,直接在Java代码中手动设置adSize和adUnitId,确保调用loadAd前属性已配置:

    adView = findViewById(R.id.adView);
    adView.setAdSize(AdSize.BANNER);
    adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
    
  • 更新Google Ads SDK依赖
    在Module级别的build.gradle中使用最新稳定版的Ads SDK依赖:

    implementation 'com.google.android.gms:play-services-ads:22.6.0'
    

    旧版本可能存在XML属性解析的兼容性问题。

  • 清理重建项目
    执行Build -> Clean Project,再执行Build -> Rebuild Project,清除编译缓存后重新运行,避免缓存导致的属性未生效问题。

内容的提问来源于stack exchange,提问作者Bata Kos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:05:24