将Interstitial AD放在浮动操作按钮上不起作用

时间:2017-04-03 15:41:25

标签: java android admob floating-action-button interstitial

我尝试将插页式广告放在我的浮动操作按钮上,所以我做了以下操作:

在我的MainActivity的onCreate中,我写道:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AdRequest adRequest = new AdRequest.Builder().build();

        mInterstitialAd = new InterstitialAd(MainActivity.this);
        mInterstitialAd.setAdUnitId("My ID");
        mInterstitialAd.loadAd(adRequest);


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                displayInterstitial();
                Snackbar.make(view, "Danke für deine Unterstützung <3", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

我也在MainActivity中编写了这个方法:

    public void displayInterstitial() {

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                if(mInterstitialAd.isLoaded()){
                    mInterstitialAd.show();
                }

            }

            @Override
            public void onAdClosed() {
            }
        });
    }
}

此代码有什么问题?如果点击浮动操作按钮,为什么我的非页内广告不显示?

1 个答案:

答案 0 :(得分:0)

在您的代码中,广告将在您创建AdListener对象之前加载。

您应该先在onCreate()方法中设置侦听器,然后在单击按钮后调用mInterstitialAd.loadAd(adRequest)

更改您的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mInterstitialAd = new InterstitialAd(MainActivity.this);
    mInterstitialAd.setAdUnitId("My ID");
    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            super.onAdLoaded();
            if(mInterstitialAd.isLoaded()){
                mInterstitialAd.show();
            }

        }

        @Override
        public void onAdClosed() {
        }
    });

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            displayInterstitial();
            Snackbar.make(view, "Danke für deine Unterstützung <3", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

 public void displayInterstitial() {
    AdRequest adRequest = new AdRequest.Builder().build();
    mInterstitialAd.loadAd(adRequest);
 }

点击后只需等待几秒即可加载广告。