Show how to use extension function to handle recyclerView item and subItem listeners.
There are different ways to handle recyclerView item click listener, today I am going to use kotlin extension function to handle the item click listener and different listeners for sub view in the recycleView cell.
- Row (item) click listener
- SubView click listener
- CompoundButton onCheckedChanged listener Code
//RadioButton, Checkbox, Switch
fun RecyclerView.addOnCheckedChangeListener(onCheckedChangeListener: OnCheckedChangeListener) {
this.addOnChildAttachStateChangeListener(object : RecyclerView.OnChildAttachStateChangeListener {
override fun onChildViewAttachedToWindow(view: View) {
val holder = getChildViewHolder(view)
for (index in 0 until (view as ViewGroup).childCount) {
val subview = view.getChildAt(index)
if(subview is CompoundButton) {
subview.setOnCheckedChangeListener { compoundButton, b ->
onCheckedChangeListener.onCheckedChanged(compoundButton, b, holder.adapterPosition)
}
}
}
}
override fun onChildViewDetachedFromWindow(view: View) {
for (index in 0 until (view as ViewGroup).childCount) {
val subview = view.getChildAt(index)
if(subview is CompoundButton) {
subview.setOnCheckedChangeListener (null)
}
}
}
})
- RadioGroup onCheckedChanged listener Code
fun RecyclerView.addOnRadioGroupCheckedChangeListener(onRadioGroupCheckedChangeListener: OnRadioGroupCheckedChangeListener) {
this.addOnChildAttachStateChangeListener(object : RecyclerView.OnChildAttachStateChangeListener {
override fun onChildViewAttachedToWindow(view: View) {
val holder = getChildViewHolder(view)
for (index in 0 until (view as ViewGroup).childCount) {
val subview = view.getChildAt(index)
if (subview is RadioGroup) {
subview.setOnCheckedChangeListener { group, buttonId ->
onRadioGroupCheckedChangeListener.onCheckedChanged(group, buttonId, holder.adapterPosition)
}
}
}
}
override fun onChildViewDetachedFromWindow(view: View) {
for (index in 0 until (view as ViewGroup).childCount) {
val subview = view.getChildAt(index)
if (subview is RadioGroup) {
subview.setOnCheckedChangeListener(null)
}
}
}
})
}