androidkotlinandroid-recyclerviewonitemclicklistener

define recyclerview click NOT as a member of constructor


from reading many website im aware that the optimal way handling onclick on recycerview was to set clicklistener not in OnBindViewHolder, its either in onCreateViewHolder(explained in here) or pass the clickListener in "bind" method(explained in here).

but one thing that really bother me, was how clickListener handled in activity / fragment

val adapter : MyAdapter(){
//click goes here
}

it may be not much but, honestly its not so so readable

i prefer to handle click listener not in constuctor, but with on separate method, meyabe like this

adapter.onItemClickListner = {
val adapter = MyAdapter()
//click more readable, yay!
}

but im not sure, if its will affect performance or not, or do i really need to stick with click on constructor?


Solution

  • I myself have used this method before.. Instead of passing the listener in the constructor, I have set it explicitly from the method call as you described. When I used that approach I had to make sure in the adapter that i checked for initialization of the listener and its null safety. So, you'll have to make sure before calling that it's absolutely present and initialized before calling the listener methods in the adapter.

    I gradually moved to constructor as I didn't want to have such conscious checks all over my adapter before any click. (When there were like multiple clickable views.)