2

I have an Activity with a layout that includes an AdView with ads:adSize="SMART_BANNER". This sits at the bottom of the screen, below a custom WebView. Now, the WebView has content that is rendered based on the space (pixel dimensions) available to it. So before I render the WebView content I need to know what size (height in particular) the SMART_BANNER will be taking up, and what is therefore left for the WebView. From here it is stated that the smart banner can have a height that is any one of 32dp, 50dp and 90dp.

So far as I can understand, I need to wait for the format of the AdView to be decided before I can render the WebView. How can I do that? Maybe by setting an AdListener? However, the methods of AdListener only seem to allow me to determine e.g. when an ad has been loaded... I don't want to have to wait for the ad to be loaded, I only want to wait for the actual size of the ad to be allocated.

I know I can avoid all this by setting the AdView to BANNER, with a fixed height of 50dp, and this does indeed work fine. But I would prefer SMART_BANNER mainly because the height can shrink to 32dp in landscape mode on a small phone screen, leaving more room for actual content.

drmrbrewer
  • 11,491
  • 21
  • 85
  • 181

1 Answers1

7

AdView has no API to retrieve its size before the Ad has actually loaded and the class is final, so you cannot implement it yourself either.

To determine the banner height dynamically you need to use an AdListener as you suspected.

Another alternative is to use static values (from the documentation) chosen dynamically according to the screen height of the device:

32 dp where height ≤ 400 dp

50 dp where height > 400 dp and ≤ 720 dp

90 dp where height > 720 dp

(you can check this answer for determining the screen height and this one for converting between px and dp values)

For example you could use something like this in your Activity:

private int getSmartBannerHeightDp() {
    DisplayMetrics dm = getResources().getDisplayMetrics();
    float screenHeightDp = dm.heightPixels / dm.density;

    return screenHeightDp > 720 ? 90 : screenHeightDp > 400 ? 50 : 32;
}
earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
  • Excellent, very helpful. I found that the `onAdLoaded()` method of `AdListener` is a good hook to use. If I wait for that and render the custom `WebView` from there, it all works nicely. In particular, it doesn't appear to have to wait until the ad is fully loaded, but seems to fire when the view opens to it's intended size... I haven't done any detailed analysis of the timings, but the overall flow appears to be good enough for my purposes. – drmrbrewer Oct 30 '18 at 17:25