Created
August 14, 2021 02:55
-
-
Save SamueldaCostaAraujoNunes/7f81123b0e65fa150e843b663bb39e9f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class BaseListAdapter<T, U : ViewDataBinding>( | |
callback: DiffUtil.ItemCallback<T> | |
) : ListAdapter<T, BaseViewHolder<T, U>>(callback) { | |
abstract fun bindItem(item: T, viewBinding: U) | |
override fun onCreateViewHolder( | |
parent: ViewGroup, | |
viewType: Int | |
): BaseViewHolder<T, U> { | |
val binding = BaseViewHolder.create(parent) | |
return BaseViewHolder(binding, BaseListAdapter<T, U>::bindItem) | |
} | |
override fun onBindViewHolder( | |
holder: BaseViewHolder<T, U>, | |
position: Int | |
) { | |
val item = getItem(position) | |
holder.bind(item) | |
} | |
} | |
class BaseViewHolder<T, U : ViewDataBinding>( | |
private val binding: U, | |
private val bindStrategy: (item: T, viewBinding: U) -> Unit | |
) : RecyclerView.ViewHolder(binding.root) { | |
companion object { | |
fun create(parent: ViewGroup): U = | |
U.inflate(LayoutInflater.from(parent.context), parent, false) | |
} | |
fun bind(item: T) = bindStrategy(item, binding) | |
} | |
class NoteAdapter : BaseListAdapter<Note, ItemNoteBinding>( | |
object : DiffUtil.ItemCallback<Note>() { | |
override fun areItemsTheSame(oldItem: Note, newItem: Note): Boolean = | |
oldItem.id == newItem.id | |
override fun areContentsTheSame(oldItem: Note, newItem: Note): Boolean = oldItem == newItem | |
} | |
) { | |
override fun bindItem(item: Note, viewBinding: ItemNoteBinding) { | |
viewBinding.note = item | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment