经过一番折腾后找到了自己的答案。它避免了硬编码的值,让我纯粹在 xml 中创建 AdView。以下为感兴趣的人提供:
我创建了 AdView 的这个子类:
public class MyAdView extends AdView {
public MyAdView(Activity activity, AdSize adSize, String adUnitId) {
super(activity, adSize, adUnitId);
// TODO Auto-generated constructor stub
}
public MyAdView(Activity activity, AdSize[] adSizes, String adUnitId) {
super(activity, adSizes, adUnitId);
// TODO Auto-generated constructor stub
}
public MyAdView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MyAdView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Context ctx=getContext();
AdSize testSize=AdSize.createAdSize(AdSize.SMART_BANNER, ctx); //Need to do this because the final static variable SMART_BANNER has buggy behaviour and returns a negative size if you don't.
int height=testSize.getHeightInPixels(ctx);
int width=testSize.getWidthInPixels(ctx);
setMeasuredDimension(width, height);
}
}
并将 xml 视图更改为(ids 再次更改):
<packagename.MyAdView
android:id="@id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="SMART_BANNER"
ads:adUnitId="unitId"
ads:loadAdOnCreate="true"
ads:testDevices="deviceId"
android:visibility="visible" >
</packagename.MyAdView>
在我的布局中包含这个,我现在得到了我的 AdView 的固定大小,没有任何代码。