Skip to content

Commit

Permalink
feat: 新增 removeAtRange() 方法,用于便捷删除指定范围内的数据
Browse files Browse the repository at this point in the history
  • Loading branch information
limuyang2 committed Nov 21, 2023
1 parent 8d2532f commit 2c2ac7e
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,27 @@ abstract class BaseDifferAdapter<T : Any, VH : RecyclerView.ViewHolder>(
}
}

override fun removeAtRange(range: kotlin.ranges.IntRange) {
if (range.isEmpty()) {
return
}
if (range.first >= items.size) {
throw IndexOutOfBoundsException("Range first position: ${range.first} - last position: ${range.last}. size:${items.size}")
}

val last = if (range.last >= items.size) {
items.size - 1
} else {
range.last
}

val list = items.toMutableList()
for (it in last downTo range.first) {
list.removeAt(it)
}
submitList(list)
}

override fun swap(fromPosition: Int, toPosition: Int) {
if (fromPosition in items.indices || toPosition in items.indices) {
items.toMutableList().also {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,37 @@ abstract class BaseQuickAdapter<T : Any, VH : RecyclerView.ViewHolder>(
removeAt(index)
}

/**
* 删除给定范围内的数据
*
* @param range Int 索引范围
*/
open fun removeAtRange(range: kotlin.ranges.IntRange) {
if (range.isEmpty()) {
return
}
if (range.first >= items.size) {
throw IndexOutOfBoundsException("Range first position: ${range.first} - last position: ${range.last}. size:${items.size}")
}

val last = if (range.last >= items.size) {
items.size - 1
} else {
range.last
}

for (it in last downTo range.first) {
mutableItems.removeAt(it)
}

notifyItemRangeRemoved(range.first, last - range.first + 1)

// 处理空视图的情况
if (displayEmptyView()) {
notifyItemInserted(0)
}
}

/**
* Item swap
* 数据位置交换。这里单纯的只是两个数据交换位置。(注意⚠️,这里移动后的数据顺序与 [move] 不同)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ abstract class BaseSingleItemAdapter<T : Any, VH : RecyclerView.ViewHolder>(priv
throw RuntimeException("Please use setItem()")
}

override fun removeAtRange(range: IntRange) {
throw RuntimeException("Please use setItem()")
}

override fun removeAt(position: Int) {
throw RuntimeException("Please use setItem()")
}
Expand Down

0 comments on commit 2c2ac7e

Please sign in to comment.