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

Android Kotlin Toolbar颜色设置:View Binding替代findViewById适配问题

问题原因

你之前通过findViewById获取的是id=toolbar的<include>标签对应外层ConstraintLayout(也就是Toolbar布局的根容器),而切换View Binding时你给内层的viewImageToolbar(Toolbar控件本身)加顶部padding,操作对象不匹配才导致异常。

解决方案

直接给include对应的外层容器设置padding,和你原来findViewById的逻辑完全一致即可:

override fun onWindowsInsetsChanged(view: View, insets: WindowInsets, padding: InitialPadding) {
    with(binding) {
        // 操作对象为include标签对应的Toolbar根布局
        toolbar.updatePadding(top = topInset)

        editObjectiveNameRoot.updatePadding(
            bottom = insets.systemWindowInsetBottom
        )
    }
}

异常逻辑说明

  • 给toolbar.viewImageToolbar加padding:Toolbar内部的标题是跟随Toolbar上下居中对齐的,给Toolbar加顶部padding后,Toolbar整体高度变大,标题居中位置下移,就会出现错位。
  • 给根布局fragmentEditObjectiveNameRoot加padding:相当于整个页面内容整体下移了状态栏高度,状态栏会露出底层窗口背景色,自然出现颜色不一致的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:15:03