Create an Admob native ad programmatically

Yoann Hercouet picture Yoann Hercouet · May 23, 2016 · Viewed 7.9k times · Source

I am trying to setup native ads from Admob programmatically but there is nearly no documentation about it from the official guide available here. I think I am close to the solution but I don't see how to set the unit size on it.

The documentation says:

Publishers can also use the FULL_WIDTH constant when programmatically creating an AdSize for a NativeExpressAdView.

The problem is that this FULL_WIDTH unit is not an AdSize unit like the other ones available, it just returns an integer.

Here is what I got for now:

mAdmobNativeExpressAdview = new NativeExpressAdView(this);
mAdmobNativeExpressAdview.setAdUnitId(getString(R.string.mediation_native_id));
mAdmobNativeExpressAdview.setAdSize(AdSize.FULL_WIDTH);

But the last line cannot be implemented since the setAdSize is expecting an AdSize object.

Is there another way to set this attribute?

Answer

t0mm13b picture t0mm13b · May 23, 2016

Look at the sample found in the documentation

mNativeExpressAdView.setAdSize(new AdSize(400, 100));

Where

AdSize constructor is declared as

AdSize(int width, int height)

Create a new AdSize.

In your code:

mAdmobNativeExpressAdview.setAdSize(new AdSize(AdSize.FULL_WIDTH, 20));

For example, sets the advert size to take up the full width, with height of 20dp.

Adjust to suit your layout.