Skip to content

Validate itemViewType on size change  #5

@t7costa

Description

@t7costa

Need to check that itemViewType is the same for the entire data set during onItemRangeInserted/Removed. Since itemViewType can be dependent on position, it is possible for views outside of the notified range to change. Calling notifyDataSetChanged() instead would result in the correct behavior (at the cost of rebinding every view), but if you want to keep the behavior consistent with RecyclerView, you should validate items outside of the range and rebind items whose itemViewType has changed.

val items = (0..10).toMutableList()
val adapter = object : RecyclerView.Adapter<MyViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        MyViewHolder(TextView(parent.context))

    override fun getItemCount() = items.size

    override fun getItemViewType(position: Int) = position % 2

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        (holder.itemView as TextView).text = items[position].toString()
        holder.itemView.setBackgroundColor(
            if (getItemViewType(position) == 0) Color.GREEN else Color.RED)
    }
}
list.adapter = adapter

button.setOnClickListener {
    items.removeAt(4)
    adapter.notifyItemRangeRemoved(4, 1)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions