简体   繁体   中英

Making Admob Native express ad dynamic

I am integrating Admob Native express ad in my application. I want it to show in all size of devices. In small devices it is not showing because of ad size. My add is in listview and gridView. Please suggest me, how it will load add in each size of device. Even I was trying to set size dynamically, but did not Work for me.

Thanks in advance.

I had success with the following code:

private LinearLayout mAdContainer;
private NativeExpressAdView mAdmobAdView;
private AdRequest mAdmobAdRequest;

[...]

private void loadAds() {
    // find out the width of the device in dp
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    float deviceWidthInDp = displayMetrics.widthPixels / displayMetrics.density;

    int adWidth = (int)(deviceWidthInDp);

    if (mAdmobAdView != null) {
      // prevents a crash on older devices
      mAdmobAdView.clearAnimation();
    }
    mAdContainer.removeAllViews();
    mAdmobAdView = new NativeExpressAdView(this);
    mAdmobAdView.setAdSize(new AdSize(adWidth, 250)); // AdSize(width, height), height ranges from 80 to 1200
    mAdContainer.addView(mAdmobAdView);
    mAdmobAdView.setAdUnitId(getString(R.string.admob_id)); // set your admob id
    mAdmobAdRequest = new AdRequest.Builder()
            .build();
    mAdmobAdView.loadAd(mAdmobAdRequest);
}

EDIT: thanks to fattire for pointing out to clear the animation before removing the view to prevent a crash on older devices (see here )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM