Skip to content

Instantly share code, notes, and snippets.

@cscouto
Created April 17, 2018 19:26
Show Gist options
  • Save cscouto/9bb0f9d2faa5a7ab1d0d5389530ca4cd to your computer and use it in GitHub Desktop.
Save cscouto/9bb0f9d2faa5a7ab1d0d5389530ca4cd to your computer and use it in GitHub Desktop.
KOTLIN - Class to implement RecyclerView Click and Longclick
/*
* Copyright (c) 2018. Couto Code
*/
package com.coutocode.allgifts.Utils
/**
* Created by docouto on 4/17/18.
*/
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
class RecyclerViewTouchListener(
context: Context,
recyclerView: RecyclerView,
private val clickListener: RecyclerViewTouchListener.ClickListener?)
: RecyclerView.OnItemTouchListener {
private val gestureDetector: GestureDetector
init {
gestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean {
return true
}
override fun onLongPress(e: MotionEvent) {
val child = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child))
}
}
})
}
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
val child = rv.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child))
}
return false
}
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
interface ClickListener {
fun onClick(view: View, position: Int)
fun onLongClick(view: View?, position: Int)
}
}
@Luix0718
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment