Android的AdMob的横幅上添加画布之上?画布、横幅、Android、AdMob

2023-09-08 08:43:47 作者:寄个春天给你

我已经用帆布一个小游戏,现在我想在画布的顶部显示AdMob广告。在AdMob网站的例子说明我做到以下几点:

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:

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?

推荐答案

您不得不设置包含广告和画布作为内容视图的父布局。修改您的code如下:

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);

}