Updated in 05 - 2019
I think the most elegant solution is to give this responsibility to recyclerView and not to view or even adapt it.
for that we need:
1: Create RecyclerItemClickListener file
class RecyclerItemClickListener(
private val mRecycler: RecyclerView,
private val clickListener: ((position: Int, view: View) -> Unit)? = null,
private val longClickListener: ((position: Int, view: View) -> Unit)? = null
) : RecyclerView.OnChildAttachStateChangeListener {
override fun onChildViewDetachedFromWindow(view: View) {
view.setOnClickListener(null)
view.setOnLongClickListener(null)
}
override fun onChildViewAttachedToWindow(view: View) {
view.setOnClickListener { v -> setOnChildAttachedToWindow(v) }
}
private fun setOnChildAttachedToWindow(v: View?) {
if (v != null) {
val position = mRecycler.getChildLayoutPosition(v)
if (position >= 0) {
clickListener?.invoke(position, v)
longClickListener?.invoke(position, v)
}
}
}
}
2: Create/Add extensions for RecyclerView:
import android.support.v7.widget.RecyclerView
import com.app.manager.internal.common.RecyclerItemClickListener
@JvmOverloads
fun RecyclerView.affectOnItemClicks(onClick: ((position: Int, view: View) -> Unit)? = null, onLongClick: ((position: Int, view: View) -> Unit)? = null) {
this.addOnChildAttachStateChangeListener(RecyclerItemClickListener(this, onClick, onLongClick))
}
3: And finally the use (i suppose you use kotlinx)
import kotlinx.android.synthetic.main.{your_layout_name}.*
class FragmentName : Fragment() {
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
recycler.affectOnItemClick { position, view -> /*todo*/ }
}
}