I'm trying to implement a Recycleview with different ItemTouchHelper for each item on the list.
The only way that I know is to add an ItemTouchHelper directly to the RecycleView and not to the item.
Example of what I'm trying to do:
I have a list with 4 items and all items I can swipe to the left.
The first item will show a delete button.
The second item will show a delete button and edit button.
The third item shows a delete button.
The fourth item shows a copy, a delete, and an edit button.
*The list can have a lot of items.
Does someone know how to do that?
The idea
So basically your your question is about how to add a unique
ItemTouchHelperto eachRecyclerViewitem based on the item type.Without going deeply into the details of how you want each item to differ in the
ItemTouchHelperswipe action, like you said to add some button functionalities like copy, edit, and delete. I will be just to the point How to differItemTouchHelper's swipe for different items.Steps
Step 1: Differentiate among
RecyclerViewitems using a POJO fieldSo, first you need to create a field in your POJO (typically an
intorenum) that differentiates among different items.Step 2: Implement a custom
ItemTouchHelper.SimpleCallbackCreate a custom
ItemTouchHelper.SimpleCallbackclass that takes the list of theRecyclerViewitems into its constructor.Next, override
onChildDraw()which is called byItemTouchHelperonRecyclerView'sonDraw()callback; and this is the right place as it's called whenever the RecyclerView draws its individual items.So, in this method you can implement how you want each item looks like when you swipe. And as it takes a ViewHolder instance, so you can get the swiped item position with
ViewHolder.getAdapterPosition(), and from the provided list of items, you can get the swiped item of this paritcular positon.Example
Here is a simple example that is a list of colors that reflects the background color whenever you swipe a certain item.
This is how it looks like:
POJO
For the above mentioned step 1, I store the value into
colorValuefieldRecyclerView adapter (no fancy code)
Custom ItemTouchHelper.SimpleCallback
Activity