Don
Don

Reputation: 1

how to include banner ad on SurfaceView ?

I'm using surface view in my android app (no any XML for that activity). I want to include banner ad in that activity. how to include banner ad on surface view

Upvotes: 0

Views: 709

Answers (1)

Nana Ghartey
Nana Ghartey

Reputation: 7927

You should post your game's main activity. To integrate banner ads on surface views programmatically, you use a RelativeLayout or a FrameLayout as your parent layout, and define the layout parameters for the adView to be positioned (for example at the bottom center of the screen) :

 @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);
        adView.setBackgroundColor(Color.TRANSPARENT); 
        // 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);

        //Request full screen
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //Create a displayMetrics object to get pixel width and height
        metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        width = metrics.widthPixels;
        height = metrics.heightPixels;

        //Create and set GL view (OpenGL View)
        myView = new MyGLSurfaceView(MainActivity.this);
     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);


        //Create a copy of the Bundle
        if (savedInstanceState != null){
            newBundle = new Bundle(savedInstanceState);         
        }

        //Set main renderer             
        setContentView(layout);

}

Upvotes: 1

Related Questions