The ad size and ad unit ID must be set before loadAd when set programmatically

前端 未结 7 1719
有刺的猬
有刺的猬 2020-12-14 00:01

I have no idea what is going on here but I am trying to set my ad unit ID dynamically through code like below and removing it from the XML but still get the error:

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 00:30

    I have made it like this

    
    
    
    
    
    
    
    

    in code

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newone);
        initAdsAccount();
        initAds();
    }
    
    private void initAdsAccount()
    {
        String accountId = AdsConstants.my_fake_ads_account_id;
    
        if (AdsConstants.isAdsMode)
        {
            accountId = AdsConstants.my_ads_account_id;
        }
    
        MobileAds.initialize(this, accountId);
    }
    
    private void initAds()
    {
        findViewById(R.id.ll_main_screen_container).post(//
                new Runnable()
                {
                    @Override
                    public void run()
                    {
                        LinearLayout adContainer = findViewById(R.id.ll_main_screen_container);
                        AdView mAdView = new AdView(MainActivity.this);
                        mAdView.setAdSize(AdSize.BANNER);
    
                        if (AdsConstants.isAdsMode)
                        {
                            mAdView.setAdUnitId(AdsConstants.main_screen_bottom_banner_id);
                        }
                        else
                        {
                            mAdView.setAdUnitId(AdsConstants.fake_banner_id);
                        }
    
                        adContainer.addView(mAdView);
                        AdRequest adRequest = new AdRequest.Builder().build();
                        mAdView.loadAd(adRequest);
                    }
                }//
        );
    }
    

提交回复
热议问题