2016-04-30 69 views
1

我不確定爲什麼,但由於某種原因,在我調用AdView.loadAd(AdRequest)時我的應用中,我的應用輸出W/Ads: Required XML attribute "adSize" was missing.然後與 java.lang.IllegalStateException: The ad size and ad unit ID must be set before loadAd is called.崩潰,即使在我的xml佈局文件中,我已經定義了adSize。 有何建議?java.lang.IllegalStateException:必須在調用loadAd之前設置廣告尺寸和廣告單元ID

XML佈局文件

 <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:id="@+id/linearLayout" 
      android:background="@android:color/white" 
      android:orientation="vertical" 
      android:padding="2dp" 
      android:paddingTop="10dp"> 

      <com.google.android.gms.ads.AdView 
       android:id="@+id/adView" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       ads:adSize="BANNER" 
       ads:adUnitId="****************" /> 
     </LinearLayout> 

Java代碼的

AdView ad = (AdView) findViewById(R.id.adView); 
    AdRequest adRequest = new AdRequest.Builder() 
      .addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build(); 
    ad.loadAd(adRequest); 

回答

0

之前調用loadAd()方法設置的廣告尺寸和橫幅ID編程,:

AdView ad = (AdView) findViewById(R.id.adView); 
//Set the Ad Size  
ad.setAdSize(AdSize.BANNER); 
//Set the Banner Id 
ad.setAdUnitId(YOUR_BANNER_ID);  
AdRequest adRequest = new AdRequest.Builder() 
       .addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build(); 
     ad.loadAd(adRequest); 

將您的布​​局更改爲:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@android:color/white" 
      android:orientation="vertical" 
      android:padding="2dp" 
      android:paddingTop="10dp"> 

     <RelativeLayout 
      android:id="@+id/adView" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"/> 

</RelativeLayout> 
+0

您的答案解決了崩潰問題,但出於某種原因顯示了廣告橫幅:缺少必需的XML屬性「adSize」。 –

+0

請務必添加設置adSize:ad.setAdUnitId(YOUR_BANNER_ID);並再次建立您的項目! =) – Jorgesys

+0

hmm我添加了ad.setAdUnitId(YOUR_BANNER_ID);但由於某種原因,它仍然顯示必需的XML屬性「adSize」丟失。 –