First of all, I saw this question: Adding a colored background with text/icon under swiped row when using Android's RecyclerView
However, even though the title s
Using the ItemTouchUiUtil interface provides a robust solution to this. It allows you to have a foreground and background view in your ViewHolder and delegate all the swipe handling to the foreground view. Here is an example that I use for swipe right to remove.
In your ItemTouchHelper.Callback :
public class ClipItemTouchHelper extends ItemTouchHelper.SimpleCallback {
...
@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
if (viewHolder != null){
final View foregroundView = ((ClipViewHolder) viewHolder).clipForeground;
getDefaultUIUtil().onSelected(foregroundView);
}
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView,
RecyclerView.ViewHolder viewHolder, float dX, float dY,
int actionState, boolean isCurrentlyActive) {
final View foregroundView = ((ClipViewHolder) viewHolder).clipForeground;
drawBackground(viewHolder, dX, actionState);
getDefaultUIUtil().onDraw(c, recyclerView, foregroundView, dX, dY,
actionState, isCurrentlyActive);
}
@Override
public void onChildDrawOver(Canvas c, RecyclerView recyclerView,
RecyclerView.ViewHolder viewHolder, float dX, float dY,
int actionState, boolean isCurrentlyActive) {
final View foregroundView = ((ClipViewHolder) viewHolder).clipForeground;
drawBackground(viewHolder, dX, actionState);
getDefaultUIUtil().onDrawOver(c, recyclerView, foregroundView, dX, dY,
actionState, isCurrentlyActive);
}
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder){
final View backgroundView = ((ClipViewHolder) viewHolder).clipBackground;
final View foregroundView = ((ClipViewHolder) viewHolder).clipForeground;
// TODO: should animate out instead. how?
backgroundView.setRight(0);
getDefaultUIUtil().clearView(foregroundView);
}
private static void drawBackground(RecyclerView.ViewHolder viewHolder, float dX, int actionState) {
final View backgroundView = ((ClipViewHolder) viewHolder).clipBackground;
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
//noinspection NumericCastThatLosesPrecision
backgroundView.setRight((int) Math.max(dX, 0));
}
}
}
And in your layout file, define the foreground and background views:
...