23

How can i create an admob smart banner with code? my layout is completely build with code.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sujith S Manjavana
  • 1,417
  • 6
  • 33
  • 60

2 Answers2

27

You can do it more or less like this:

LinearLayout adContainer = <container>;
AdView adView = new AdView(activity)
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId(<your-publisher-id>); //ca-app-pub-3940256099942544/6300978111 (admob sample banner ad id)

// Initiate a generic request to load it with an ad
AdRequest adRequest = new AdRequest();
adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
adView.loadAd(adRequest);

// Place the ad view.
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
adContainer.addView(adView, params);
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
matiash
  • 54,791
  • 16
  • 125
  • 154
  • 21
    since AdMob API has changed user:\n adView = new AdView(activity);\n adView.setAdSize(AdSize.BANNER);\n adView.setAdUnitId("myAdUnitId");\n – MemLeak Aug 18 '14 at 07:59
  • 3
    Interesting that the improvement comment has many times more votes than the answer. Edit made. – QED Mar 14 '16 at 19:35
  • AdRequest like this --> AdRequest adRequest = new AdRequest.Builder().addTestDevice("4C9AED4DAD2042C84C4AE85B421D9648").build(); – Ranjithkumar Jan 24 '17 at 11:46
  • You should use 'Ad unit ID' instead of publisher id in adView.setAdUnitId – Harsh Kothari Nov 22 '20 at 15:43
0

Add this in your Activity

//Add this in OnCreate of Activity to initialize the ad
MobileAds.initialize(getApplicationContext(), "< your-ad-unit-Id >");
//Add this wherever your code needs to add the ad

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);

//Additionally to adjust the position to Bottom
layout.setGravity(Gravity.BOTTOM);

// Create a banner ad
mAdView = new AdView(this);
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.setAdUnitId("<your-ad-unit-Id>");

// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();

// Optionally populate the ad request builder.
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);

// Add the AdView to the view hierarchy.
layout.addView(mAdView);

// Start loading the ad.
mAdView.loadAd(adRequestBuilder.build());

setContentView(layout);

Then check if you have given the permissions in Manifest

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

Add meta data below inside < application > in Manifest

<meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />

And finally check if you have added required dependency to compile in app gradle

compile 'com.google.android.gms:play-services:9.6.1'


Prateekro
  • 566
  • 1
  • 6
  • 28