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

Android Kotlin:跳转Fragment返回后MaterialToolbar高度为0的问题

问题分析与解决方案

原因

  • 从Fragment B返回Fragment A时,Fragment A的视图虽已重建,但onViewCreated()的执行时机早于MaterialToolbar的布局测量完成时机。首次打开Fragment A时,视图是从头走完完整布局流程,测量已经结束,所以能拿到正确高度;但返回时视图恢复过程中,onViewCreated()先执行,此时Toolbar还没完成测量,直接调用height就会返回0。
  • 如果你的MaterialToolbar是动态调整高度(比如跟随RecyclerView滚动变化、依赖内容动态调整),返回时布局状态尚未更新,也会导致测量值未被正确计算。

解决方法

方法1:监听Toolbar布局完成事件

通过ViewTreeObserver监听Toolbar的布局变化,等测量完成后再获取高度:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val toolbar = view.findViewById<MaterialToolbar>(R.id.toolbar)
    toolbar.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            // 移除监听避免重复触发
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                toolbar.viewTreeObserver.removeOnGlobalLayoutListener(this)
            } else {
                toolbar.viewTreeObserver.removeGlobalOnLayoutListener(this)
            }
            val toolbarHeight = toolbar.height
            // 在这里执行需要用到高度的逻辑
        }
    })
}

方法2:用post()延迟获取高度

利用View的post()方法,把获取高度的操作放到UI队列末尾,此时布局已经完成:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val toolbar = view.findViewById<MaterialToolbar>(R.id.toolbar)
    toolbar.post {
        val toolbarHeight = toolbar.height
        // 处理高度相关逻辑
    }
}

方法3:监听窗口内边距(适配系统栏场景)

如果Toolbar高度受系统窗口内边距影响,可通过监听窗口内边距变化来获取最终高度:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val toolbar = view.findViewById<MaterialToolbar>(R.id.toolbar)
    toolbar.setOnApplyWindowInsetsListener { v, insets ->
        val appliedInsets = v.onApplyWindowInsets(insets)
        val toolbarHeight = v.height
        // 在这里使用获取到的高度
        appliedInsets
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:30:33