更新当前的选中状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private fun updateSelectStatus(curUser: User) {
mAdapter.run {
var targetPosition = -1
var previousCheckedPosition = -1

// 遍历一次,同时更新状态并记录位置
data.forEachIndexed { index, user ->
val wasChecked = user.isChecked
val shouldBeChecked = (user.uid == curUser.uid)
if (wasChecked != shouldBeChecked) {
user.isChecked = shouldBeChecked
if (shouldBeChecked) {
targetPosition = index
} else {
previousCheckedPosition = index
}
}
}

// 安全地滚动到目标位置
if (targetPosition != -1) {
mBinding.rvUser.smoothScrollToPosition(targetPosition)
}

// 精确通知变化
if (previousCheckedPosition != -1) {
notifyItemChanged(previousCheckedPosition)
}
if (targetPosition != -1 && targetPosition != previousCheckedPosition) {
notifyItemChanged(targetPosition)
}
}
}