Search code examples
javaandroidadmobpositioning

AdMob banner positioning in Android on bottom of the screen using no-xml relative layout


This code below positions the AdMob banner on the bottom of the view. But the problem is that I have used LinearLayout and moved the banner up by 75 pixels. This is bad, as the banner height is usually 50px, but after moving it 50px up then it shows only part of the banner. Another problem is that the banner height is not fixed.

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;
int screenHeight = displaymetrics.heightPixels;
LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams(screenWidth, 2 * screenHeight - 75);


 // Create an ad.
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);

// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
    .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
    .build();

// Start loading the ad in the background.
adView.loadAd(adRequest);

// Adding full screen container
addContentView(adView, adParams);

I have tried to use RelativeLayout instead of LinearLayout like this:

RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT, 
        RelativeLayout.LayoutParams.WRAP_CONTENT);


lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

..................
......................
addContentView(adView, lay);

But this shows the banner on the top of the screen. How can I bring it to the bottom?


Solution

  • AdRequest adRequest = new AdRequest.Builder()
      .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
      .build();
    
    RelativeLayout relativeLayout = new RelativeLayout(this);
    mFrameLayout.addView(relativeLayout);
    
    
    RelativeLayout.LayoutParams adViewParams = new RelativeLayout.LayoutParams(
       AdView.LayoutParams.WRAP_CONTENT,
       AdView.LayoutParams.WRAP_CONTENT);
     // align bottom
    adViewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
     // align center
    adViewParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
    
    
    relativeLayout.addView(adView, adViewParams);
    
    
    adView.loadAd(adRequest);
    adView.setBackgroundColor(Color.BLACK);
    adView.setBackgroundColor(0);
    

    Where mFrameLayout in my case is defined in cocos2d-x Cocos2dxActivity class and is defined as follows:

        // FrameLayout
        ViewGroup.LayoutParams framelayout_params =
            new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                       ViewGroup.LayoutParams.MATCH_PARENT);
        mFrameLayout = new FrameLayout(this);
        mFrameLayout.setLayoutParams(framelayout_params);