-
Notifications
You must be signed in to change notification settings - Fork 0
/
CommonViewHolder.kt
43 lines (37 loc) · 1.4 KB
/
CommonViewHolder.kt
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
34
35
36
37
38
39
40
41
42
43
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
abstract class CommonViewHolder<out E>(binding: ViewBinding) : RecyclerView.ViewHolder(binding.root) {
abstract fun onBindView(item: @UnsafeVariance E)
@PublishedApi
internal fun getItemPosition(): Int? {
return bindingAdapterPosition.takeIf { it != RecyclerView.NO_POSITION }
}
@PublishedApi
internal fun getItem(position: Int): Any? {
val adapter =
bindingAdapter as? ListAdapter<*, *> ?: throw IllegalAccessException("This function can only be used on ViewHolders inside a ListAdapter.")
return try {
adapter.currentList[position]
} catch (e: Exception) {
null
}
}
@Suppress("UNCHECKED_CAST")
inline fun getItem(action: (item: E) -> Unit) {
getItemPosition()?.let { index ->
val item = (getItem(index) as? E) ?: return
action(item)
}
}
@Suppress("UNCHECKED_CAST")
inline fun getItemIndexed(action: (index: Int, item: E) -> Unit) {
getItemPosition()?.let { index ->
val item = (getItem(index) as? E) ?: return
action(index, item)
}
}
}
open class ViewOnlyViewHolder(binding: ViewBinding) : CommonViewHolder<Nothing>(binding) {
final override fun onBindView(item: Nothing) = Unit
}