Implement "stable ID" for candidate adapters

prevent crash in FlexboxLayoutManager and hopefully improves performance
ref: https://github.com/google/flexbox-layout/issues/363#issuecomment-382949953
This commit is contained in:
Rocka 2025-09-21 18:19:20 +08:00
parent cf4fb49edc
commit bc2d6735f5
No known key found for this signature in database
GPG Key ID: 28031158FFDD6853
3 changed files with 17 additions and 0 deletions

View File

@ -43,6 +43,13 @@ class PagedCandidatesUi(
}
private val candidatesAdapter = object : RecyclerView.Adapter<UiHolder>() {
init {
setHasStableIds(true)
}
override fun getItemId(position: Int): Long =
data.candidates[position].hashCode().toLong()
override fun getItemCount() =
data.candidates.size + (if (data.hasPrev || data.hasNext) 1 else 0)
@ -98,6 +105,7 @@ class PagedCandidatesUi(
adapter = candidatesAdapter
layoutManager = candidatesLayoutManager
overScrollMode = View.OVER_SCROLL_NEVER
itemAnimator = null
}
@SuppressLint("NotifyDataSetChanged")

View File

@ -163,6 +163,7 @@ class HorizontalCandidateComponent :
}
}.apply {
id = R.id.candidate_view
itemAnimator = null
adapter = this@HorizontalCandidateComponent.adapter
layoutManager = this@HorizontalCandidateComponent.layoutManager
addItemDecoration(FlexboxVerticalDecoration(dividerDrawable))

View File

@ -21,6 +21,10 @@ import splitties.views.setPaddingDp
open class HorizontalCandidateViewAdapter(val theme: Theme) :
RecyclerView.Adapter<CandidateViewHolder>() {
init {
setHasStableIds(true)
}
var candidates: Array<String> = arrayOf()
private set
@ -36,6 +40,10 @@ open class HorizontalCandidateViewAdapter(val theme: Theme) :
override fun getItemCount() = candidates.size
override fun getItemId(position: Int): Long {
return candidates[position].hashCode().toLong()
}
@CallSuper
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CandidateViewHolder {
val ui = CandidateItemUi(parent.context, theme)