Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate itemViewType on size change #5

Open
t7costa opened this issue Oct 1, 2018 · 0 comments
Open

Validate itemViewType on size change #5

t7costa opened this issue Oct 1, 2018 · 0 comments

Comments

@t7costa
Copy link
Contributor

t7costa commented Oct 1, 2018

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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant