Skip to content

Instantly share code, notes, and snippets.

@VassilisPallas
Last active May 8, 2016 14:55
Show Gist options
  • Save VassilisPallas/57757639605589345cc5096f9a8fcad7 to your computer and use it in GitHub Desktop.
Save VassilisPallas/57757639605589345cc5096f9a8fcad7 to your computer and use it in GitHub Desktop.
Click and Long click listener for RecycleView
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);
}
}
@VassilisPallas
Copy link
Author

To Add the listener to the recycle view just write

mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
              // on click
            }

            @Override
            public void onItemLongClick(View view, int position) {
              // on long click
            }
        }));

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