使用AdListener将广告视图添加到布局

时间:2014-04-14 18:46:14

标签: android adview

我只想在加载横幅时显示我的广告,但如果我使用此代码,则始终退出我的应用。在logcat中,它说我应该使用removeview(),但我只是这样做?! 有我的oncreate代码:

        final LinearLayout layout =  (LinearLayout) findViewById(R.id.mainLayout);
        if (adView != null) {
            adView.destroy();
            layout.removeView(adView);
        }
        // Create the adView.
        adView = new AdView(getApplicationContext());

        adView.setAdUnitId("**********************");
        adView.setAdSize(AdSize.SMART_BANNER);

// Initiate a generic request.
        AdRequest adRequest = new AdRequest.Builder().build();

// Load the adView with the ad request.
        adView.setBackgroundColor(Color.BLACK);
        adView.loadAd(adRequest);
        adView.setAdListener(new AdListener() {
            public void onAdLoaded() {
                layout.addView(adView);
            }
        });

我的logcat:

04-14 20:43:18.632  30414-30414/de.**************** E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.****************, PID: 30414
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
        at android.view.ViewGroup.addViewInner(ViewGroup.java:3759)
        at android.view.ViewGroup.addView(ViewGroup.java:3612)
        at android.view.ViewGroup.addView(ViewGroup.java:3557)
        at android.view.ViewGroup.addView(ViewGroup.java:3533)
        at de.****************.MainActivity$1.onAdLoaded(MainActivity.java:120)
        at com.google.android.gms.internal.x.onAdLoaded(Unknown Source)
        at com.google.android.gms.internal.af$a.onTransact(Unknown Source)
        at android.os.Binder.transact(Binder.java:361)
        at yf.c(SourceFile:152)
        at xx.s(SourceFile:717)
        at xx.a(SourceFile:429)
        at aau.run(SourceFile:212)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5356)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
        at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

onAdLoaded()方法无法正常工作一次。第二次加载时尝试添加相同的视图。

public void onAdLoaded() {
            layout.addView(adView);
        }

解决方案

全局变量

private boolean OnLoad;

示例方法

adView.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
                if(!OnLoad)
                {
                ((LinearLayout) findViewById(R.id.main_layout1)).addView(adView);
                OnLoad=true;
                }
        }

脚注:布尔值的默认值为false。