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

使用Data Binding实现RecyclerView多类型ViewHolder的问题咨询

问题1:多数据类场景下手动填充RecyclerView数据

你已经用密封类InfoRecyclerViewItems作为所有列表项的父类,填充数据直接构造不同子类的实例加入列表即可,示例如下:

步骤1:构造测试数据并绑定Adapter

在MainActivity的onCreate方法中补充如下代码:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    // 1. 构造混合类型的数据源
    val itemList = mutableListOf<InfoRecyclerViewItems>().apply {
        // 添加带图类型的项
        add(InfoRecyclerViewItems.WithPicture(1, "星际穿越", "科幻题材天花板,五维空间设定极具想象力"))
        add(InfoRecyclerViewItems.WithPicture(2, "流浪地球2", "国产工业化科幻里程碑,细节非常扎实"))
        // 添加不带图类型的项
        add(InfoRecyclerViewItems.WithoutPicture(3, "泰坦尼克号", "影史经典爱情片,每次重看都有新感受"))
        add(InfoRecyclerViewItems.WithoutPicture(4, "阿甘正传", "人生必看影片,普通人的奋斗史非常动人"))
        // 可以按需求任意添加两种类型的项,顺序随意
    }

    // 2. 初始化适配器并绑定到RecyclerView
    val adapter = RecyclerViewAdapter(itemList)
    binding.recyclerView.apply {
        setHasFixedSize(true)
        layoutManager = LinearLayoutManager(this@MainActivity)
        this.adapter = adapter
    }
}

可选优化:给Adapter加数据更新方法

如果后续需要动态更新列表,在Adapter中新增更新方法,避免重复创建Adapter实例:

// 在RecyclerViewAdapter类中添加
fun updateData(newList: List<InfoRecyclerViewItems>) {
    infoItems1.clear()
    infoItems1.addAll(newList)
    notifyDataSetChanged()
}
// 更高性能可以搭配DiffUtil实现局部刷新,不需要重绘整个列表

另外建议把密封类的两个子类改为data class,后续用DiffUtil比对数据的时候会更方便:

sealed class InfoRecyclerViewItems{
    data class WithPicture (
        val id: Int,
        val movieName: String,
        val thoughts: String
    ): InfoRecyclerViewItems()
    data class WithoutPicture(
        val id: Int,
        val movieName: String,
        val thoughts: String
    ): InfoRecyclerViewItems()
}

问题2:Adapter判断对应视图类型的逻辑

你当前的实现已经是标准的正确逻辑,完整的判断链路是:

  1. 重写getItemViewType方法:根据当前位置的条目所属的密封类子类类型,返回对应布局的ID作为视图类型标记
  2. onCreateViewHolder拿到传入的viewType参数,直接匹配返回对应布局的ViewHolder即可
  3. onBindViewHolder中判断ViewHolder的实际类型,绑定对应类型的数据即可

这套逻辑不会出现类型匹配错误,因为密封类的子类类型是有限且可穷举的,when表达式可以覆盖所有场景,不需要额外的兜底判断(如果是kotlin 1.7+的版本,when表达式覆盖所有密封类子类的情况下不需要写else分支)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:27:02