有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java以编程方式设置adsize不适用于NativeAdExpress

我的广告XML代码是

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

我使用以下代码以编程方式设置adsize

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.安卓.gms.ads.NativeExpressAdView
    安卓:id="@+id/adView"
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content"
    app:adUnitId="ca-app-pub-3940256099942544/1072772517"
    app:adSize="320x250"/>

但我想动态设置广告宽度


共 (2) 个答案

  1. # 1 楼答案

    我正在动态设置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());
             }
        });
    }
    

    可能需要在加载add之前设置add unit id

    希望这对你有帮助

  2. # 2 楼答案

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