必须在调用 loadAd 之前设置广告尺寸和广告单元 ID

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

我已经在 Whosebug 上查看了其他问题,但我的情况不符合任何一个。我已经设置了单元大小和单元 ID,并且只调用一次构建。怎么了?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <com.google.android.gms.ads.AdView
        android:id="@+id/topAdView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        ads:adUnitId="@string/topAdUnitID">
    </com.google.android.gms.ads.AdView>
</RelativeLayout>

这是我的广告创建函数

public class TopAd  extends Fragment {
    private AdView topAdView;
    @Override
    public void onActivityCreated(Bundle bundle) {
        super.onActivityCreated(bundle);

        // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
        // values/strings.xml.
        topAdView = (AdView) getView().findViewById(R.id.topAdView);
        topAdView.setAdSize(AdSize.SMART_BANNER);

        // Create an ad request. Check logcat output for the hashed device ID to
        // get test ads on a physical device. e.g.
        // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .build();

        // Start loading the ad in the background.
        topAdView.loadAd(adRequest);
    }
}

当我运行时,应用程序崩溃并在行 "topAdView.loadAd(adRequest);" 上显示错误 "The ad size and ad unit ID must be set before loadAd is called"。我做错了什么?

在 xml 中给出广告尺寸而不是代码, 例如

ads:adSize="BANNER"

并删除这一行

topAdView.setAdSize(AdSize.SMART_BANNER);

希望对您有所帮助。

干杯 -阿曼