我正在尝试通过编程方式将adUnitId设置为新的Google Play服务(旧AdMob)的广告.
我在XML中使用(在< include>)中使用):
<com.google.android.gms.ads.AdView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="http://schemas.android.com/apk/res-auto" android:id="@+id/adView" android:layout_width="match_parent" android:layout_height="wrap_content" ads:adSize="BANNER"/>
这在onCreate()中:
AdView mAdview = (AdView)findViewById(R.id.adView); mAdview.setAdUnitId(((App)getApplication()).getAdmobKey()); mAdview.setAdListener(new AdListener() { @Override public void onAdLoaded() { super.onAdLoaded(); findViewById(R.id.adView).setVisibility(View.VISIBLE); } }); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .build(); mAdview.loadAd(adRequest);
我得到:
The ad size and ad unit ID must be set before loadAd is called.
所以第二个选择是以编程方式制作广告.
新的XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/adView" />
新代码:
AdView mAdview = new AdView(this); ... ((LinearLayout)findViewById(R.id.adView)).addView(mAdview); mAdview.loadAd(adRequest);
但我得到同样的错误.
我也尝试从com.google.android.gms.ads.AdView继承自定义视图,但它是最终的.
任何建议?
解决方法
当loadAd发生时,loadAd()方法检查if(mAdView.getAdSize()== null || mAdView.getAdUnitID()== null)).
尝试在调用loadAd以确定其状态之前记录(mAdView.getAdSize()== null || mAdView.getAdUnitID()== null)的布尔输出:
mAdView = new AdView(this); mAdView.setAdSize(AdSize.BANNER); mAdView.setAdUnitId(AD_UNIT_ID); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .build(); if(mAdView.getAdSize() != null || mAdView.getAdUnitID() != null) mAdView.loadAd(adRequest); // else Log state of adsize/adunit ((LinearLayout)findViewById(R.id.adView)).addView(mAdview);