I have created a small game using Canvas, and now I want to display AdMob ads on top of the canvas. The Example on the AdMob site suggests I do the following:
// Create an ad.
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
layout.addView(adView);
However, I am setting the contentView to a Custom Canvas that I created as follows:
setContentView(new CanvasView(this));
CanvasView:
public class CanvasView extends View {
public CanvasView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
...
How can I display AdMob ads on top of my Custom Canvas?
You'd have to set the parent layout containing the ad and canvas as the content view. Modify your code as follows:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ad.
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// Create an ad request.
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(TestDeviceID)
.build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
//Optional - Request full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Create canvas view
View myView = new CanvasView(this);
//define ad view parameters
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layout.addView(myView);
layout.addView(adView, adParams);
//Set main renderer
setContentView(layout);
}
Instead of Ad Banners, Try Interstitial Ads so that Ad will automatically populate over the View.
// Create ad request
AdRequest adRequest = new AdRequest();
InterstitialAd interstitial = new InterstitialAd(getActivity(), AD_UNIT_ID);
// Begin loading your interstitial
interstitial.loadAd(adRequest);
// Set Ad Listener to use the callbacks below
interstitial.setAdListener(this);
Make sure your class should implements AdListener.