Skip to content

Instantly share code, notes, and snippets.

@shubhamnikam
Last active July 6, 2019 18:37
Show Gist options
  • Save shubhamnikam/4e0cfecad7d84795effafd9aa38b398e to your computer and use it in GitHub Desktop.
Save shubhamnikam/4e0cfecad7d84795effafd9aa38b398e to your computer and use it in GitHub Desktop.
RecyclerView Swipe Right/Left
private void deleteTodoItem() {
//Swipe to delete currentTodo Item
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
//private Drawable icon = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon_delete);
private ColorDrawable background = new ColorDrawable(Color.RED);
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
mTodoAdapter.deleteCurrentTodoItem(position);
// showMySnackBar("Todo deleted");
}
@Override
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
@NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY,
int actionState, boolean isCurrentlyActive) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
View itemView = viewHolder.itemView;
int backgroundCornerOffset = 20;
if (dX > 0) { // Swiping to the right
background.setBounds(itemView.getLeft(), itemView.getTop(),
itemView.getLeft() + ((int) dX) + backgroundCornerOffset,
itemView.getBottom());
} else if (dX < 0) { // Swiping to the left
background.setBounds(itemView.getRight() + ((int) dX) - backgroundCornerOffset,
itemView.getTop(), itemView.getRight(), itemView.getBottom());
} else { // view is unSwiped
background.setBounds(0, 0, 0, 0);
}
background.draw(c);
}
}).attachToRecyclerView(mRecyclerView);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment