我使用Canvas创建了一个小游戏,现在我想在画布上显示AdMob广告。 AdMob网站上的示例建议我执行以下操作:
// 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);
但是,我将contentView设置为我创建的自定义画布,如下所示:
setContentView(new CanvasView(this));
CanvasView:
public class CanvasView extends View {
public CanvasView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
...
如何在自定义画布上显示AdMob广告?
答案 0 :(得分:4)
您必须将包含广告和画布的父布局设置为内容视图。修改您的代码如下:
@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);
}
答案 1 :(得分:0)
尝试非页内广告,而不是广告横幅广告,以便广告自动填充在视图上。
//制作广告请求
AdRequest adRequest = new AdRequest();
InterstitialAd interstitial =新的InterstitialAd(getActivity(),AD_UNIT_ID);
//开始加载您的插页式广告
interstitial.loadAd(AdRequest中);
//设置广告侦听器以使用下面的回调
interstitial.setAdListener(本);
确保您的课程应该实现AdListener。