Android Studio Swipe Delete RecyclerView Page
The Swipe Delete RecyclerView page is a common feature in Android Studio that allows users to delete items in a RecyclerView through a simple swipe gesture. This feature provides a quick and easy way to manage lists of items in an app.
Syntax
To implement Swipe Delete for a RecyclerView, the following library must be added to the app's build.gradle file:
implementation 'com.android.support:recyclerview-v7:28.0.0'
This library provides support for both the RecyclerView and Swipe-to-Dismiss functionality.
In the RecyclerView Adapter, the following code sample shows how to add support for swipe delete in your RecyclerView:
val simpleItemTouchCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
// method not required for Swipe Delete
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
adapter.removeAt(position)
}
}
val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback)
itemTouchHelper.attachToRecyclerView(recyclerView)
Example
The Swipe Delete RecyclerView can be seen in many apps, including Google Keep. In Google Keep, users can swipe a note card to archive it, which removes it from the main view but keeps it accessible in the Archive folder.
Output
The expected output of the Swipe Delete RecyclerView is for the RecyclerView item to be swiped off-screen and removed from the list. Upon swipe, the item should animate off the screen and the list of items should adjust to show the new number of items in the list.
Explanation
When a user swipes an item in the RecyclerView, the onSwiped()
callback method is triggered. In this method, the position of the swiped item is obtained from the adapter position of the ViewHolder and the item is removed from the dataset using the removeAt()
function call. The itemTouchHelper
is then instructed to attach to the RecyclerView.
Use
The Swipe Delete RecyclerView is a useful feature for any app that displays a list of items that the user may want to delete. This feature can be used for to-do lists, note-taking apps, shopping lists, and more.
Important Points
- The Swipe Delete action should be done with one finger, making it easily accessible.
- The undo action should be available after the deletion, in case of accidental swipes.
- A confirmation message or dialog may be displayed before deleting the item, to give users a chance to change their minds.
- The Swipe Delete RecyclerView is not recommended for lists that have a fixed number of items.
Summary
The Swipe Delete RecyclerView is a simple and effective way to delete items in a list using a swipe gesture. This feature is easy to implement using the provided library and can be used in a variety of apps that need to manage lists of items.