我的广告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"/>
我使用以下代码以编程方式设置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:必须在调用loadAd之前设置广告尺寸和广告单元ID。
我尝试这样做时效果很好
<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"/>
但我想动态设置广告宽度
答案 0 :(得分: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());
答案 1 :(得分:0)
我正在动态设置广告并且工作正常。 以下是我的代码。
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。
希望这会对你有所帮助。