From c1039b966283e64b954b11edf7fc1d1654af9339 Mon Sep 17 00:00:00 2001 From: cp-megh Date: Tue, 23 Jan 2024 18:07:08 +0530 Subject: [PATCH] Fix invalid view holder adapter position exception --- .../adapter/ComposeRecyclerViewAdapter.kt | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/compose-recyclerview/src/main/java/com/example/compose_recyclerview/adapter/ComposeRecyclerViewAdapter.kt b/compose-recyclerview/src/main/java/com/example/compose_recyclerview/adapter/ComposeRecyclerViewAdapter.kt index aa7f94c..31cb7dc 100644 --- a/compose-recyclerview/src/main/java/com/example/compose_recyclerview/adapter/ComposeRecyclerViewAdapter.kt +++ b/compose-recyclerview/src/main/java/com/example/compose_recyclerview/adapter/ComposeRecyclerViewAdapter.kt @@ -16,15 +16,13 @@ class ComposeRecyclerViewAdapter : fun getItemType(position: Int): Int } + private var itemList: MutableList = mutableListOf() + var totalItems: Int = 0 set(value) { if (field == value) return field = value - if (field == -1) { - notifyItemInserted(0) - } else { - notifyItemChanged(0) - } + notifyItemRangeChange(value) } var itemBuilder: (@Composable (index: Int) -> Unit)? = @@ -80,4 +78,16 @@ class ComposeRecyclerViewAdapter : this.itemTypeBuilder = it } } + + private fun notifyItemRangeChange(newSize: Int) { + val oldSize = itemList.size + if (newSize < oldSize) { + itemList = itemList.subList(0, newSize) + notifyItemRangeRemoved(newSize, oldSize - newSize) + } else if (newSize > oldSize) { + val list = MutableList(newSize - oldSize) { Any() } + itemList = (itemList + list).toMutableList() + notifyItemRangeInserted(oldSize, newSize - oldSize) + } + } } \ No newline at end of file