Swiping to Remove Items
In the previous sections, we learned how to present different view types. However, up until now, we have worked with a fixed list of items. What if you want to be able to remove items from the list? There are a few common mechanisms to achieve that—fixed delete buttons, swipe to delete, and long-click to select then a "click to delete" button, to name a few. In this section, we will focus on the "swipe to delete" approach.
Let's start by adding the deletion functionality to our adapter. To tell the adapter to remove an item, we need to indicate which item we want to remove. The simplest way to achieve this is by providing the position of the item. In our implementation, this will directly correlate to the position of the item in our listData
list. So, our removeItem(Int)
function should look like this:
fun removeItem(position: Int) { listData.removeAt(position) ...