Skip to content

Instantly share code, notes, and snippets.

@neonankiti
Last active October 28, 2018 04:57
Show Gist options
  • Save neonankiti/57eb5c8c3bfbfe2379796f3b47cccc6b to your computer and use it in GitHub Desktop.
Save neonankiti/57eb5c8c3bfbfe2379796f3b47cccc6b to your computer and use it in GitHub Desktop.
Template for Android RecyclerView
data class SomeObject(val id: Int)
class SampleRecyclerViewAdapter(private val listener: SampleOnClickListener?) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var items = mutableListOf<SomeObject>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = when (viewType) {
VIEW_TYPE_SAMPLE -> SampleViewHolder.create(LayoutInflater.from(parent.context), parent, listener)
else -> throw IllegalArgumentException("$viewType is unexpected here.")
}
override fun getItemCount(): Int = items.size
override
fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) = when (holder) {
is SampleViewHolder -> {
}
else -> {
}
}
@Synchronized
fun addAll(newList: List<SomeObject>) {
synchronized(items) {
val diffUtils = DiffUtil.calculateDiff(SampleDiffUtil(items, newList))
items = newList.toMutableList()
diffUtils.dispatchUpdatesTo(this)
}
}
companion object {
private const val VIEW_TYPE_SAMPLE = 1
}
}
typealias SampleOnClickListener = (SomeObject?) -> Unit
class SampleViewHolder private constructor(itemView: View, listener: SampleOnClickListener?) :
RecyclerView.ViewHolder(itemView) {
fun bind(any: SomeObject) {
// TODO do your job
}
companion object {
private const val LAYOUT = R.layout.abc_action_menu_item_layout
fun create(inflater: LayoutInflater, parent: ViewGroup?, listener: SampleOnClickListener?) =
SampleViewHolder(inflater.inflate(LAYOUT, parent, false), listener)
}
}
class SampleDiffUtil(
private val oldList: List<SomeObject>,
private val newList: List<SomeObject>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
//TODO ID除いたその他の値のequal比較をオブジェクトごとに比較する
oldList[oldItemPosition].hashCode() == newList[newItemPosition].hashCode()
override
fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
oldList[oldItemPosition].id == newList[newItemPosition].id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment