Android: Dynamically Load An AdMob Ad in an Android View

2/28/2014 4:18:59 AM

The following will dynamically load an AdMob ad. The LoadAds() method should be placed wthin the onCreate method of your activity. The beginning code shows the layout that the ad is added to.

<LinearLayout
	android:id="@+id/main_adTopBanner"
	android:orientation="vertical" 
	android:layout_height="50dp"
	android:layout_width="match_parent">        
</LinearLayout>


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

	LoadAds();			    	   
}
	
private AdView AD_TOP_BANNER = null;
public void LoadAds()
{
	// Create the adView.
	this.AD_TOP_BANNER = new AdView(this);
	this.AD_TOP_BANNER.setAdUnitId("MY_SPECIAL AND_UNIQUE_AD_ID");
	// this.AD_TOP_BANNER.setAdSize(AdSize.BANNER);
	this.AD_TOP_BANNER.setAdSize(AdSize.SMART_BANNER);

	// Lookup your LinearLayout assuming it's been given	
	LinearLayout layout = (LinearLayout) findViewById(R.id.main_adTopBanner);

	// Add the adView to it.
	layout.addView(this.AD_TOP_BANNER);

	// Initiate a generic request.
	AdRequest adRequest = null;
	adRequest = new AdRequest.Builder().build();
	//FOR TESTING AND LOADING TEST ADS
	//adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4").build();	

	// Load the adView with the ad request.
	this.AD_TOP_BANNER.loadAd(adRequest);
}