Last active
May 8, 2016 14:55
-
-
Save VassilisPallas/57757639605589345cc5096f9a8fcad7 to your computer and use it in GitHub Desktop.
Click and Long click listener for RecycleView
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.content.Context; | |
import android.support.v7.widget.RecyclerView; | |
import android.view.GestureDetector; | |
import android.view.MotionEvent; | |
import android.view.View; | |
/** | |
* Created by vasilis on 10/30/15. | |
*/ | |
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener { | |
private OnItemClickListener mListener; | |
private GestureDetector mGestureDetector; | |
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) { | |
mListener = listener; | |
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { | |
@Override | |
public boolean onSingleTapUp(MotionEvent e) { | |
return true; | |
} | |
@Override | |
public void onLongPress(MotionEvent e) { | |
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY()); | |
if (childView != null && mListener != null) { | |
mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView)); | |
} | |
} | |
}); | |
} | |
@Override | |
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { | |
View childView = rv.findChildViewUnder(e.getX(), e.getY()); | |
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { | |
mListener.onItemClick(childView, rv.getChildAdapterPosition(childView)); | |
} | |
return false; | |
} | |
@Override | |
public void onTouchEvent(RecyclerView rv, MotionEvent e) { | |
} | |
@Override | |
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { | |
} | |
public static interface OnItemClickListener { | |
public void onItemClick(View view, int position); | |
public void onItemLongClick(View view, int position); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To Add the listener to the recycle view just write