Created
August 24, 2018 13:06
-
-
Save hitesh-dhamshaniya/4754bc584b635b8e39217a9304277125 to your computer and use it in GitHub Desktop.
RecyclerViewTouchListener ( Add item click listener to Recyclerview easily) with Kotlin Language support.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.view.GestureDetector; | |
import android.view.MotionEvent; | |
import android.view.View | |
import android.view.ViewGroup | |
import androidx.recyclerview.widget.RecyclerView; | |
public class RecyclerViewTouchListener(val mRecyclerView:RecyclerView) : RecyclerView.OnItemTouchListener { | |
private var mClickListener:ClickListener?=null; | |
private var mLongClickListener:LongClickListener? =null; | |
private lateinit var mGestureDetector:GestureDetector; | |
init { | |
setupGestureController(mRecyclerView); | |
} | |
constructor(mRecyclerView:RecyclerView, listener:ClickListener):this(mRecyclerView){ | |
mClickListener = listener | |
} | |
constructor(mRecyclerView:RecyclerView, listener:LongClickListener):this(mRecyclerView){ | |
mLongClickListener = listener | |
} | |
public fun setClickListener(listener:ClickListener) { | |
this.mClickListener = listener; | |
} | |
public fun setLongClickListener(listener:LongClickListener) { | |
this.mLongClickListener = listener; | |
} | |
private fun setupGestureController(recycleView:RecyclerView ){ | |
mGestureDetector = GestureDetector(recycleView.context, object:GestureDetector.SimpleOnGestureListener() { | |
override fun onSingleTapUp(e: MotionEvent?): Boolean { | |
return true | |
} | |
override fun onLongPress(e: MotionEvent?) { | |
val child = recycleView.findChildViewUnder(e!!.getX(), e.getY()); | |
if (child != null && mLongClickListener != null) { | |
mLongClickListener?.onItemLongClick(recycleView, child, recycleView.getChildAdapterPosition(child)); | |
} | |
} | |
}); | |
} | |
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean { | |
val child = rv.findChildViewUnder(e.getX(), e.getY()); | |
if (child != null && mClickListener != null && mGestureDetector.onTouchEvent(e)) { | |
mClickListener?.onItemClick(rv, child, rv.getChildAdapterPosition(child)); | |
} | |
return false; | |
} | |
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) { | |
} | |
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { | |
} | |
interface ClickListener { | |
fun <T : ViewGroup> onItemClick(parent: T, view: View, position: Int) | |
} | |
interface LongClickListener { | |
fun <T : ViewGroup> onItemLongClick(parent: T, view: View, position: Int) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How add listener to Recyclerview:
rv_home_topics.addOnItemTouchListener(listener)