Android AdMob without XML

后端 未结 2 581
暗喜
暗喜 2021-01-25 07:44

I have a massive question to ask as I am really stuck on this and it would be create to get ads on my free application, ok first off I have been following this book

Begi

相关标签:
2条回答
  • 2021-01-25 07:57

    I tried it last night and got cool result, see my code in Oncreate() of your Activity:

     LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setGravity(Gravity.BOTTOM|Gravity.CENTER);
    
        // Create a banner ad
        mAdView = new AdView(this);
        mAdView.setAdSize(AdSize.SMART_BANNER);
        mAdView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
    
    
    
        // Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
        MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
    
    
    
        /*For Test On Real Device*/
        AdRequest adRequest=  new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    
    
    
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setId(R.id.linear);
        linearLayout.setGravity(Gravity.BOTTOM | Gravity.CENTER);
    
    
        LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 9f);
        layoutParams1.gravity = Gravity.TOP;
        view.setLayoutParams(layoutParams1);
    
        int heightPixels = AdSize.FULL_BANNER.getHeightInPixels(this);
    
        LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, heightPixels, 0f);
        layoutParams2.gravity = Gravity.BOTTOM;
        mAdView.setLayoutParams(layoutParams2);
    
        layout.addView(view);
        layout.addView(mAdView);
    
    
        // Start loading the ad.
        setContentView(layout);
    

    this will show you the ads at the bottom, GL ;)

    0 讨论(0)
  • 2021-01-25 08:02

    Create a layout container and put the AdView and the renderView in it:

    RelativeLayout layout = new RelativeLayout(this);
    AdView adView = new AdView(this, AdSize.BANNER, "a151bf25136cf46");
    layout.addView(renderView);
    layout.addView(adView);
    setContentView(layout);
    adView.loadAd(new AdRequest());
    

    EDIT 2020:

    Code above is 7 years old and the Google Mobile Ads SDK has changed a lot since then. Here's a minimal code example against the current latest SDK version.

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    AdView adView = new AdView(this);
    adView.setAdSize(AdSize.BANNER);
    adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
    adView.loadAd(new AdRequest.Builder().build());
    setContentView(layout);
    
    0 讨论(0)
提交回复
热议问题