这个技巧对我有用。
- 将您的 AdView 放置在某个布局中
布局.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Don't create AdView now. Programatically set AdView -->
</LinearLayout>
- 在您的活动或片段上访问 AdView 的父布局(即此处的线性布局)并添加 addOnGlobalLayoutListener
LinearLayout layout = findViewById(R.id.container);
layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// load your ad here
AdView adView = new AdView(context);
adView.setAdUnitId("YOUR_AD_UNIT");
// create custom banner size with same aspect ratio as type banner
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int targetAdWidth = (int) (layout.getWidth() / displayMetrics.density);
int targetAdHeight = targetAdWidth * 50 / 320;
AdSize adSize = new AdSize(targetAdWidth, targetAdHeight);
adView.setAdSize(adSize);
layout.addView(adView);
AdRequest.Builder adReq = new AdRequest.Builder();
AdRequest adRequest = adReq.build();
// add listener if required
adView.setAdListener(adListener);
adView.loadAd(adRequest);
layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});