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

如何将RecyclerView.Adapter的synthetic引用替换为ViewBinding

RecyclerView Adapter 集成 ViewBinding 改造方案

适配前置步骤

  • 第一步:确认模块已开启ViewBinding特性,在模块级构建配置文件中添加如下配置:
    Gradle Groovy写法:
    android {
        buildFeatures {
            viewBinding true
        }
    }
    
    Gradle KTS写法:
    android {
        buildFeatures {
            viewBinding = true
        }
    }
    
  • 第二步:改造ViewHolder定义,直接持有对应布局的ViewBinding实例,无需单独存储itemView
  • 第三步:修改onCreateViewHolder的布局加载逻辑,直接用Binding类的inflate方法加载布局
  • 第四步:调整onBindViewHolder的控件调用逻辑,通过ViewHolder持有的binding实例直接访问控件

完整改造后代码

class PlayersListAdapter(
    var items: ArrayList<MatchPlayer>
) : RecyclerView.Adapter<PlayersListAdapter.MatchSubstitutionHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MatchSubstitutionHolder {
        // 直接通过ViewBinding加载布局,无需单独调用LayoutInflater.inflate获取View
        val binding = ItemTeamPlayerBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return MatchSubstitutionHolder(binding)
    }

    override fun onBindViewHolder(holder: MatchSubstitutionHolder, position: Int) {
        val currentPlayer = items[position]
        // 直接通过binding访问控件,无需依赖synthetic或者手动findViewById
        holder.binding.lblPlayerName.text = currentPlayer.name
        // 其余控件赋值逻辑同理
    }

    // ViewHolder接收Binding实例,父类构造传入binding.root作为itemView
    class MatchSubstitutionHolder(val binding: ItemTeamPlayerBinding) : RecyclerView.ViewHolder(binding.root)

    override fun getItemCount(): Int = items.size
}

注意:ItemTeamPlayerBinding是系统根据布局文件名item_team_player.xml自动生成的绑定类,如果你使用的布局文件名不同,类名会自动按驼峰转换后拼接Binding后缀生成。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:54:00