Recyclerview: pass listener to viewholder in constructor or during binding?

from the CommonsWare Community archives

At November 3, 2020, 2:20pm, root-ansh asked:

I would oftenwrite my recycler view viewholder as :

class vh(v:View):RecyclerView.ViewHolder(v){
    
    fun bind(data:Data, onClickListener:Listener){
        ...
        itemView.setOnClickListener { onClickListener.click(data, currentItemPosition) }
    }
}

But i have also seen people add listener like this:

class vh2(v:View,val onclickListener:Listener):RecyclerView.ViewHolder(v){
    fun bind(data:Data){
        ...
        itemView.setOnClickListener { onClickListener.click(data, currentItemPosition) }
    }
}

Which method is more correct and which method is more prone to errors? From my limited knowledge, i could say:

  1. in first case , the instance of listener will be passed as param every time the view is binded, so somewhat of an extra memory would be used in comparision to the 2nd case, where the listener would be passed on 6-7 times(like view, in the oncreate)

  2. not sure about val/var case though. i feel the correct way would be to use var and nullable listeners , but again not sure. this just feels wrong as i think listeners are also getting reused(because only say 7 listeners are created because of adapter mechanism). so if we are passing data or position on click, then a lot of views would be sending back the same data/position. Would appreciate some explaination on how this approach works

  3. on a side note, if we have to send back the position of item clicked, should we use getlayoutPosition or getAdapterPosition ?


At November 3, 2020, 3:18pm, mmurphy replied:

The first approach assumes that a single listener is suitable for everything. The second approach allows for per-bind() listeners. Neither are intrinsically correct or incorrect AFAIK.

I would not make that assumption, as it will depend on where and how the listeners get created.

To be honest, I could not understand your question.

That depends entirely on what the listener needs.