You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决AdMob Adaptive Banner自适应横幅高度异常问题

解决方案

导致Adaptive Banner高度异常的核心原因为AdMob旧版本bug、过时的尺寸计算API调用、监听逻辑不严谨,和DataBinding无关,可按以下步骤修复:

  • 升级AdMob依赖版本
    你当前使用的20.2.0版本存在官方已知的自适应横幅高度计算缺陷,直接升级到21.0.0以上的稳定版即可修复多数场景下的异常:
// ADMOB
implementation "com.google.android.gms:play-services-ads:22.6.0"
  • 替换过时的AdSize计算逻辑
    你当前使用的windowManager.defaultDisplay、display.getMetrics均为Android 11起废弃的API,多设备/多系统版本下返回的屏幕尺寸存在偏差,需适配新的WindowMetrics API:
private val adSize: AdSize
    get() {
        val adWidthPixels = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val windowMetrics = windowManager.currentWindowMetrics
            val insets = windowMetrics.windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
            windowMetrics.bounds.width() - insets.left - insets.right
        } else {
            val display = windowManager.defaultDisplay
            val outMetrics = DisplayMetrics()
            @Suppress("DEPRECATION")
            display.getMetrics(outMetrics)
            outMetrics.widthPixels
        }
        val density = resources.displayMetrics.density
        val adWidth = (adWidthPixels / density).toInt()
        return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth)
    }
  • 给广告容器增加最大高度限制
    在布局的ad_view_container节点增加android:maxHeight属性,避免极端场景下广告异常拉伸占满屏幕,正常自适应横幅高度不会超过100dp:
<FrameLayout
    android:id="@+id/ad_view_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="100dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />
  • 移除冗余的OnGlobalLayoutListener监听
    当前监听触发后未移除,会导致后续布局变化时重复回调,多次计算AdSize引发异常,修改逻辑如下:
private fun initAdViewAndLoadBanner() {
    adView = AdView(this)
    // 给AdView设置正确的布局参数
    adView?.layoutParams = FrameLayout.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )
    adViewContainer.removeAllViews()
    adViewContainer.addView(adView)

    adViewContainer.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            if (!initialLayoutComplete) {
                initialLayoutComplete = true
                loadBanner()
                // 触发后移除监听
                adViewContainer.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        }
    })
}

内容的提问来源于stack exchange,提问作者Rence Rei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:12:01