必须在调用loadAd之前设置广告尺寸和广告单元ID。当我以编程方式设置横幅时

时间:2017-11-06 13:22:27

标签: java android admob banner

我正面临java.lang.IllegalStateException:必须在调用loadAd之前设置广告尺寸和广告单元ID。每当我尝试以编程方式设置Banner时。实际上,我想从java类中设置AdUnitID而不是从xml。

这是活动

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="com.example.test">

**SOME COMPONENTS**

        <RelativeLayout
            android:id="@+id/adMobView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true">

        </RelativeLayout>


</RelativeLayout>

这里是java类(oncreate)

RelativeLayout adContainer = (RelativeLayout)findViewById(R.id.adMobView);
            AdView mAdView = new AdView(this);
            mAdView.setAdSize(AdSize.SMART_BANNER);
            mAdView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
            adContainer.addView(mAdView);
            AdRequest adRequest = new AdRequest.Builder().build();
            mAdView.loadAd(adRequest);

清单

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

摇篮

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.google.android.gms:play-services-ads:11.4.2'
}

1 个答案:

答案 0 :(得分:0)

我认为您的AdMob XML代码不正确。确保在根<RelativeLayout>

中添加AdMob的xmlns

即。

<?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" //This line
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

如果您已经添加了上述代码,则需要以编程方式创建。

在您的活动java文件中:

View adContainer = findViewById(R.id.adMobView);
AdView mAdView = new AdView(context);
mAdView.setAdSize(AdSize.BANNER);
mAdView.setAdUnitId(YOUR_BANNER_ID);
((RelativeLayout)adContainer).addView(mAdView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);

在XML文件中使用它:

<RelativeLayout 
android:id="@+id/adMobView"
android:layout_width="match_parent"
android:layout_height="match_parent
android:layout_alignParentBottom="true"/>