2

My XML code for the ad is

 <com.google.android.gms.ads.NativeExpressAdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:adUnitId="YOUR_AD_ID"/>

I am setting the adsize programmatically using the following code

mAdView = (NativeExpressAdView) cardView.findViewById(R.id.adView);
int width = screenwidth - 16;
mAdView.setAdSize(new AdSize(width, 250));
AdRequest request = new AdRequest.Builder()
   .addTestDevice("YOUR_DEVICE")
   .build();
mAdView.loadAd(request);

When I run, the app crashes with the error

java.lang.IllegalStateException: The ad size and ad unit ID must be set before loadAd is called.

It works fine when I try like this

<com.google.android.gms.ads.NativeExpressAdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:adUnitId="ca-app-pub-3940256099942544/1072772517"
    app:adSize="320x250"/>

But I want to set the ad width dynamically

4

2 回答 2

1

当我以编程方式添加 NativeExpressAdView 并从 XML 中删除时,它已解决,如下所示。

mAdView = new NativeExpressAdView(this);
int width = screenwidth - 16;
mAdView.setAdSize(new AdSize(width, 250)); 
mAdView.setAdUnitId("myAdUnitId");

// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();

// Optionally populate the ad request builder.
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);

// Add the NativeExpressAdView to the view hierarchy.
layout.addView(mAdView);

// Start loading the ad.
mAdView.loadAd(adRequestBuilder.build());
于 2017-02-23T16:07:27.343 回答
0

我正在动态设置 adsize 并且它工作正常。下面是我的代码。

private void setUpAndLoadNativeExpressAds() {
    // Use a Runnable to ensure that the RecyclerView has been laid out before setting the
    // ad size for the Native Express ad. This allows us to set the Native Express ad's
    // width to match the full width of the RecyclerView.
    mRecyclerView.post(new Runnable() {
        @Override
        public void run() {
            final float scale = MainActivity.this.getResources().getDisplayMetrics().density;
            // Set the ad size and ad unit ID for each Native Express ad in the items list.
            for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
                adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
                final CardView cardView = (CardView) findViewById(R.id.ad_card_view);
                final int adWidth = cardView.getWidth() - cardView.getPaddingLeft()
                        - cardView.getPaddingRight();
                AdSize adSize = new AdSize((int) (adWidth / scale), NATIVE_EXPRESS_AD_HEIGHT);
                adView.setAdSize(adSize);
                adView.setAdUnitId(AD_UNIT_ID);
            }
            adView.loadAd(new AdRequest.Builder().build());
         }
    });
}

可能您需要在加载添加之前设置添加单元 ID。

希望这会帮助你。

于 2017-02-23T11:58:48.757 回答