Alin Alin - 3 months ago 74
Android Question

NativeExpressAdView set adSizeto work on all sizes

I am implementing native express ads in my app and I have a problem with setting the ad's width. While the height is pretty much straight forward, the width gives me trouble:

I've tried setting it like this:

adView.setAdSize(new AdSize((int) (getResources().getConfiguration().screenWidthDp - (getResources().getDimension(R.dimen.margin) / getResources().getDisplayMetrics().density)), 80));

Since ads are contained in LinearLayout which has its margin set, I can't use
so I need to calculate the width in code.

Now, the problem is that the width is not correct on all screen sizes, while on some it works fine, in other I get messages like

"Not enough space to show ad. Needs 315x80 dp, but only has 310x...."

How can I calculate the width to properly scale on all screen sizes and e sure that the ad actually displays itself?

NOTE: the add is displayed inside a LinearLayout which can be either in a regular activity layout file or in a ListView.


It's because AdSize takes dp parameters and you're converting the margins to pixels.

Also be aware of any padding that some views such as the AppCompat views add on some platforms and not others. For example CardView adds 2dp padding on each side for KitKat and below, but there is no padding added for Lollipop and above.