以编程方式设置广告大小不适用于 NativeAdExpress

Setting adsize programmatically not working for NativeAdExpress

我的 XML 广告代码是

 <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"/>

我正在使用以下代码以编程方式设置广告大小

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);

当我 运行 时,应用程序崩溃并出现错误

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

当我这样尝试时它工作正常

<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"/>

但我想动态设置广告宽度

我正在动态设置广告大小并且效果很好。 下面是我的代码。

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。

希望对您有所帮助。

当我以编程方式添加 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());