Making Admob Native express ad dynamic

2019-06-25 01:09发布

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.

标签: android admob
1条回答
We Are One
2楼-- · 2019-06-25 02:01

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)

查看更多
登录 后发表回答