当AdMob无法接收广告或接收到空广告(高度=0)时,我有同样的需求能够显示自己的广告。
我使用以下代码,基于AdView扩展RelativeLayout的事实:
mAdMobView = new AdView(pActivity, AdSize.SMART_BANNER, Constants.ADMOB_AD_UNIT_ID);
mAdMobView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(final View pV, final int pLeft, final int pTop, final int pRight, final int pBottom, final int pOldLeft, final int pOldTop, final int pOldRight, final int pOldBottom) {
final float lAdHeight = mAdMobView.getHeight();
if (lAdHeight == 0) {
Debug.i(LOG_TAG, "mAdMobView.onLayoutChange(...) mAdMobView.height='" + lAdHeight + "'. AdMob returned an empty ad !");
} else {
Debug.d(LOG_TAG, "mAdMobView.onLayoutChange(...) mAdMobView.height='" + lAdHeight + "'");
}
}
});
mAdMobView.setAdListener(new AdListener() {
@Override public void onReceiveAd(final Ad pAd) {
Debug.d(LOG_TAG, "onReceiveAd(...) AdMob ad received (mAdMobView.visibility='" + mAdMobView.getVisibility() + "').");
}
@Override public void onPresentScreen(final Ad pAd) {
Debug.d(LOG_TAG, "onPresentScreen(...)");
}
@Override public void onLeaveApplication(final Ad pAd) {
Debug.d(LOG_TAG, "onLeaveApplication(...)");
}
@Override public void onDismissScreen(final Ad pAd) {
Debug.d(LOG_TAG, "onDismissScreen(...)");
}
@Override
public void onFailedToReceiveAd(final Ad pAd, final ErrorCode pErrorCode) {
Debug.i(LOG_TAG, "onFailedToReceiveAd(...) AdMob ad error (" + pErrorCode + ").");
}
});
'onLayoutChange'中的代码每次Admob接收到新广告时都会执行。
编辑:我的答案不正确,因为该方法是在API 11中添加的...我改为使用上一个答案中解释的'onPreDraw()'。
AdSize.SMART_BANNER.getHeightInPixels(context)
非常好用,因此我可以在广告加载时动态调整布局。该函数中的内部代码实际上是智能横幅所示的相同计算 https://stackoverflow.com/a/53061092/513479。 - txedo