Created
November 14, 2019 15:53
-
-
Save buntupana/7af9dd9cbdf972d27f83b5e1bc563cbb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Generic Adapter for a list of ITEMS and a BINDING class | |
*/ | |
class SimpleListBindingAdapter<in ITEM, BINDING : ViewDataBinding> : | |
RecyclerView.Adapter<SimpleListBindingAdapter<ITEM, BINDING>.BindingHolder> { | |
private var items = listOf<ITEM>() | |
@LayoutRes | |
private var layoutRes: Int = 0 | |
var listener: OnItemClickListener<BINDING>? = null | |
set(value) { | |
field = value | |
notifyDataSetChanged() | |
} | |
constructor(layoutRes: Int) { | |
this.layoutRes = layoutRes | |
} | |
constructor(layoutRes: Int, items: List<ITEM>?) { | |
this.items = items ?: listOf() | |
this.layoutRes = layoutRes | |
} | |
init { | |
setHasStableIds(true) | |
} | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingHolder { | |
val binding = DataBindingUtil.inflate<BINDING>( | |
LayoutInflater.from(parent.context), | |
layoutRes, | |
parent, | |
false | |
) | |
if (binding == null) { | |
Timber.e("Layout resource given is not wrapped with <layout> tag") | |
} | |
return BindingHolder(binding!!) | |
} | |
override fun onBindViewHolder(holder: BindingHolder, position: Int) { | |
holder.bind() | |
} | |
override fun getItemCount(): Int = items.size | |
override fun getItemId(position: Int): Long { | |
return items[position].hashCode().toLong() | |
} | |
fun swapList(items: List<ITEM>) { | |
if (this.items != items) { | |
this.items = items | |
notifyDataSetChanged() | |
} | |
} | |
inner class BindingHolder(private val binding: BINDING) : RecyclerView.ViewHolder(binding.root), | |
View.OnClickListener { | |
init { | |
binding.root.setOnClickListener(this) | |
} | |
fun bind() { | |
binding.setVariable(BR.viewModel, items[layoutPosition]) | |
binding.executePendingBindings() | |
} | |
override fun onClick(view: View) { | |
listener?.onItemClick(binding, adapterPosition) | |
} | |
} | |
interface OnItemClickListener<BINDING : ViewDataBinding> { | |
fun onItemClick(binding: BINDING, position: Int) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment