Skip to content

Instantly share code, notes, and snippets.

@sebk
Created September 13, 2018 16:19
Show Gist options
  • Save sebk/d7c13570e6a1f2f66aa35ef9ed831f1d to your computer and use it in GitHub Desktop.
Save sebk/d7c13570e6a1f2f66aa35ef9ed831f1d to your computer and use it in GitHub Desktop.
Android RecyclerView Item Click Listener
private void addClickListener(RecyclerView recyclerView) {
recyclerView.addOnItemTouchListener(new RecycleViewItemListener(getApplicationContext(), recyclerView,
new RecyclerItemListener.RecyclerTouchListener() {
public void onClickItem(View v, int position) {
System.out.println("On Click Item interface");
}
public void onLongClickItem(View v, int position) {
System.out.println("On Long Click Item interface");
}
}));
}
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecycleViewItemListener implements RecyclerView.OnItemTouchListener {
private RecyclerTouchListener listener;
private GestureDetector gd;
public RecycleViewItemListener(Context ctx, final RecyclerView rv,
final RecyclerTouchListener listener) {
this.listener = listener;
gd = new GestureDetector(ctx,
new GestureDetector.SimpleOnGestureListener() {
@Override
public void onLongPress(MotionEvent e) {
// We find the view
View v = rv.findChildViewUnder(e.getX(), e.getY());
// Notify the even
listener.onLongClickItem(v, rv.getChildAdapterPosition(v));
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
View v = rv.findChildViewUnder(e.getX(), e.getY());
// Notify the even
listener.onClickItem(v, rv.getChildAdapterPosition(v));
return true;
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
return (child != null && gd.onTouchEvent(e));
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface RecyclerTouchListener {
public void onClickItem(View v, int position);
public void onLongClickItem(View v, int position);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment