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

如何让RecyclerView.ViewHolder的View Binding像Kotlin Synthetics一样识别XML布局高度

问题根因

你遇到的布局属性失效问题,本质是inflate方法调用方式错误,和View Binding本身的设计无关。
所有layout_前缀的XML属性都需要依赖父布局生成对应LayoutParams才能生效,你当前使用的单参数XYZBinding.inflate(layoutInflater)等价于inflate(layoutInflater, null, false),没有传入父布局parent参数,所以根布局声明的layout_height="48dp"会被直接忽略。
之前使用Kotlin synthetics时属性正常,是因为那时你inflate布局时传入了parent参数,和是否用View Binding没有关联。

修复方案

修改onCreateViewHolder中的inflate调用,使用三参数重载,传入父布局parent,同时将attachToRoot设为false(RecyclerView会负责将itemView添加到父布局,不能提前绑定):

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
    when (viewType) {
        item -> return ItemVH(StringRowBinding.inflate(layoutInflater, parent, false))
        header -> return HeaderVH(InfoHeaderBinding.inflate(layoutInflater, parent, false))
    }
    return ItemVH(StringRowBinding.inflate(layoutInflater, parent, false))
}

补充说明

完全不需要退回到findViewById,View Binding提供了多场景的inflate重载,只要调用方式正确,所有布局属性都会正常生效,不存在违背使用初衷的问题。绝大多数View Binding导致布局异常的问题,都是未正确传入parent参数导致的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:15:03