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

如何在循环填充XML的场景中将Kotlin synthetics替换为view binding

循环填充子布局的View Binding适配方案

这个场景完全支持View Binding,不需要回退到findViewById,调整方式如下:

  • 首先确认你的模块级build.gradle已经开启View Binding功能(已开启可跳过):
android {
    buildFeatures {
        viewBinding true
    }
}

开启后系统会为每个布局文件生成对应的绑定类,你的子布局R.layout.imageitem_row对应的绑定类默认名为ImageitemRowBinding,如果有自定义布局命名转换规则按你的规则调整即可。

  • 调整循环内的填充逻辑,使用子布局的绑定类完成填充、控件赋值和挂载:
// 先导入对应绑定类,包名替换为你项目的实际包名
import com.yourpackagename.databinding.ImageitemRowBinding

// 循环逻辑调整
for (item in itemList) {
    // inflate参数和你原来的LayoutInflater参数完全对应
    val itemBinding = ImageitemRowBinding.inflate(LayoutInflater.from(this), binding.linear, false)
    // 直接通过绑定类访问控件,用法和之前的Kotlin synthetics几乎一致
    itemBinding.text1.text = item.title
    itemBinding.text2.text = item.pubdate
    // 挂载绑定类对应的根View到父容器
    binding.linear.addView(itemBinding.root)
}

原理说明:所有布局文件都会生成对应的绑定类,不管是页面根布局还是复用的子项布局,绑定类会自动关联布局内所有带id的控件,自带空安全和类型安全校验,比findViewById和废弃的Kotlin synthetics稳定性更高。

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

相关产品推荐
方舟 Agent Plan

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

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