Swipe to delete in Jetpack Compose Lazy Column Android

https://android-developers.googleblog.com/2020/08/announcing-jetpack-compose-alpha.html

Hi devs in this article i am going to show you how you can achieve swipe to delete functionality in lazycolumn/ lazyrow (aka Recyclerview) in jetpack compose. In case of recyclerview with xml we need to define customer listener to listen swipe on an item but in case of jetpack compose we don’t need to define custom listener. In jetpack compose we have built in functionality to listen swipes SwipeToDismiss() inside our lazycolumn or lazyrow. You can more read about it here:

https://developer.android.com/training/wearables/components/swipe-to-dismiss

Remember one thing always use items() instead of itemsIndexed() inside lazycolumn/lazyrow to populate content of list when you are working with SwipeToDismiss. I faced unexpected error when i tried to implement SwipeToDismiss with itemsIndexed() inside my lazycolumn then on swipetodelete its deleting all items instead of just deleting single item.

Incase of working with items() you can face below exception which i faced:

java.lang.IllegalArgumentException: Key 0 was already used. If you are using LazyColumn/Row please make sure you provide a unique key for each item.

So working with items() inside lazycolum/lazyrow make sure you are generating unique key for every item which you are going to add in the lazycolumn/lazyrow.

In my example i am not fetching the list from server nor i am using static list, i am adding items in list at runtime so to avoid above exception i have delcared global variable to generate id of every item and created a data class for my item which is below:

data class NotesItem(var id:Int, var title:String)

Now how to add divider in lazycolumn/lazyrow? For this you need to define Divider() inside your lazycolumn/lazyrow

Divider(Modifier.fillMaxWidth(), Color.DarkGray)

Now SwipeToDismiss takes few parameters which are as:

state: to define current state of dismiss
modifier: to define height/width/padding etc
directions: it takes set of directions which we want to implement
1- DismissDirection.EndToStart
2- DismissDirection.StartToEnd
background: you need to define here color and icon of your swiping item
dismissThresholds: its handle on how much fractional swipe you want to change your swiping item color and item only dismiss when it current swipe matches this threshold.
dismissContent: it is responsible to show your content on screen.

Result will be:

Checkout this repository for the source code, if you like it then give it a star: