I have a RecyclerView and the items should be removed after swiping them. I solved it with the ItemTouchHelper class. In the onChildDraw method I set up a red background which appears while swiping behind the list item. On top of that there is a trash icon on the right site. It is working fine, but if you start swiping and dont swipe to the end and then swipe back to the normal position, the icon of the trash dont go away. However it goes only away when I swipe the selected item, but not on the normal items.
Here is the code of the ItemTouchHelper class:
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
@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();
rvAdapter.removeItem(position);
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive){
Bitmap icon;
if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE){
View itemView = viewHolder.itemView;
float height = (float) itemView.getBottom() - (float) itemView.getTop();
float marginRight = 10;
paint.setColor(Color.parseColor("#D32F2F"));
RectF background = new RectF((float) itemView.getRight() + dX, (float) itemView.getTop(),(float) itemView.getRight(), (float) itemView.getBottom());
c.drawRect(background,paint);
icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_delete_forever);
RectF icon_dest = new RectF((float) itemView.getRight() - marginRight - height, itemView.getTop(), itemView.getRight() - marginRight, itemView.getBottom());
c.drawBitmap(icon,null,icon_dest,paint);
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
Someone know how I can remove the icon when the swipe is cancelled? Or is there something like a z-index? Because when I swipe the selected item back the trash icon disappears under the item. But when I swipe a normal item the icon is over the item and then the icon stays there.