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

Kotlin中RecyclerView多布局使用View Binding复用单一ViewHolder的实现

完全可以实现,核心思路是在创建ViewHolder时生成对应布局的Binding实例,传入统一的ViewHolder中,利用Kotlin智能类型转换访问共有的控件属性即可,无需创建多个ViewHolder,具体实现如下:

修改后的AdapterClass.kt

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import 你的项目包名.databinding.HorizontalLayoutBinding
import 你的项目包名.databinding.VerticalLayoutBinding

class AdapterClass(private val horizontal: Boolean = false) : RecyclerView.Adapter<AdapterViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AdapterViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return if (horizontal) {
            val binding = HorizontalLayoutBinding.inflate(inflater, parent, false)
            AdapterViewHolder(binding)
        } else {
            val binding = VerticalLayoutBinding.inflate(inflater, parent, false)
            AdapterViewHolder(binding)
        }
    }

    override fun onBindViewHolder(holder: AdapterViewHolder, position: Int) {
        holder.bindImage(position)
    }

    override fun getItemCount(): Int {
        // 替换为你的列表项计数逻辑
        return 0
    }
}

修改后的AdapterViewHolder.kt

import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import 你的项目包名.databinding.HorizontalLayoutBinding
import 你的项目包名.databinding.VerticalLayoutBinding

class AdapterViewHolder(private val binding: ViewBinding) : RecyclerView.ViewHolder(binding.root) {

    fun bindImage(position: Int) {
        val color = if (itemView.isSelected) {
            itemView.context.getColor(R.color.blue)
        } else {
            itemView.context.getColor(R.color.green)
        }

        when (binding) {
            is HorizontalLayoutBinding -> {
                binding.mainContainer.setBackgroundColor(color)
                // 如需加载图片,直接操作 binding.imageView 即可
            }
            is VerticalLayoutBinding -> {
                binding.mainContainer.setBackgroundColor(color)
                // 如需加载图片,直接操作 binding.imageView 即可
            }
        }
    }
}

注意事项

  • 将代码中的你的项目包名替换为你自己项目中View Binding生成类的对应包路径
  • 如果你的布局文件名不是horizontal_layout.xml/vertical_layout.xml,对应调整Binding类的名称即可
  • 该实现为编译期安全,不会出现运行时控件找不到的异常,也没有额外的性能损耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:15:02