I have a RecyclerView and want to allow my users to use a swipe gesture to remove items from the list. But as known from other apps (e.g. Gmail), I want to show a delete icon behind it, so that my users know that swiping results in a remove. However, I can't find an obvious way to do that. The ItemTouchHelper uses the viewHolder.itemView, so it takes the whole row.
My code:
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new
ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
@Override
public boolean onMove(
final RecyclerView recyclerView,
final RecyclerView.ViewHolder viewHolder,
final RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(
final RecyclerView.ViewHolder viewHolder,
final int swipeDir) {
adapter.remove(viewHolder.getAdapterPosition());
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(
simpleItemTouchCallback
);
itemTouchHelper.attachToRecyclerView(itemsRecyclerView);
itemsRecyclerView.setLayoutManager(
new LinearLayoutManager(getContext())
);
itemsRecyclerView.setAdapter(adapter);
Has anyone a glue if this is possible at all? The only thing I can imagine right now is to extend the ItemTouchHelper / copy the code, and instead of using viewHolder.itemView I take a view identified by an ID.
use the onChildDraw() method from ItemTouchHelper - I have it working with a bitmap and coloured background for swiping left and right with different colors and icons:
96f can be replaced with whatever distance from the left/right side you'd like it to be. This isn't perfect as when I'm down to 2 items in the adapter and I remove a position the canvas does not disappear and remains until the adapter is set again - working on trying to resolve now - I'll update if I find a complete solution but for now this is what I think you're looking for.
I have done it with having the following layout structure for the recycler view item:
Then I use this view holder as base view holder in my adapter:
In my ItemTouchHelper.Callback class I extend the following methods like that:
With this approach you use one level in layouts more, but saves yourself troubles with drawing on Canvas. Also you may select other views inside the item, for example save one that was touched and return it and have children of an item also swipeable.
Attaching to the recycler view: