Android SharedPreferences Tutorial and Example

Adding Swipe to Dismiss with RecyclerView

Swipe-to-dismiss gives Android users a quick way to remove an item from a scrolling list. In a mail app, task manager or shopping list, a horizontal gesture feels faster than opening a menu and selecting Delete. With RecyclerView, the standard solution is Android’s ItemTouchHelper.

The helper connects touch gestures to a callback, allowing an item to move with the user’s finger and disappear when the swipe passes a chosen threshold. It also supports drag-and-drop, although this tutorial focuses on removing rows with a left or right swipe.

This pattern suits practical Australian apps, from a Sydney commuter’s daily task list to a Melbourne café stock tracker. It can also make better use of one-handed interaction when people are walking between platforms or checking a phone during a busy lunch break.

A reliable implementation needs more than visual movement. The underlying data set must be updated, the adapter must be notified, and the user should have a way to recover an accidental deletion. The following approach works with Java or Kotlin projects and can be adapted to SQLite, Room or an in-memory list.

Prepare The RecyclerView Data

Start with a model and adapter that expose a removable collection. The adapter should change the same list used by the screen; otherwise, the row may vanish briefly and reappear during the next refresh.

For example, a simple Kotlin adapter might contain a method like this:

class TaskAdapter(
    private val tasks: MutableList<Task>
) : RecyclerView.Adapter<TaskViewHolder>() {

    override fun getItemCount(): Int = tasks.size

    fun removeAt(position: Int): Task {
        val removed = tasks.removeAt(position)
        notifyItemRemoved(position)
        return removed
    }

    fun insertAt(position: Int, task: Task) {
        tasks.add(position, task)
        notifyItemInserted(position)
    }
}

In a production app, deletion should also be reflected in the permanent store. If tasks are loaded from SQLite or Room, remove the record there rather than relying only on notifyItemRemoved(). Tutorials and sample projects such as these Android project examples can help beginners compare adapter behaviour with database-backed screens.

Keep the adapter position current. Avoid storing a position inside a click listener because rows move after an item is removed. Use bindingAdapterPosition when responding to an interaction, and ignore the action if it equals RecyclerView.NO_POSITION.

Connect ItemTouchHelper To The List

ItemTouchHelper.SimpleCallback receives movement flags and swipe events. A callback configured with 0 for drag directions and LEFT or RIGHT for swipe directions allows horizontal dismissal without enabling accidental row rearrangement.

val callback = object : ItemTouchHelper.SimpleCallback(
    0,
    ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
) {
    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean = false

    override fun onSwiped(
        viewHolder: RecyclerView.ViewHolder,
        direction: Int
    ) {
        val position = viewHolder.bindingAdapterPosition
        if (position != RecyclerView.NO_POSITION) {
            val deleted = adapter.removeAt(position)
            showUndo(deleted, position)
        }
    }
}

ItemTouchHelper(callback).attachToRecyclerView(recyclerView)

The onMove() method returns false because dragging is disabled. onSwiped() is called only after the gesture crosses the configured dismissal threshold. The list item moves automatically while the helper manages the swipe animation.

For a right-to-left interface, you can limit the gesture to ItemTouchHelper.START, or use END where appropriate. Relative directions are usually safer than hard-coded left and right values because they respect the user’s layout direction.

Choose Between Deletion Behaviours

A swipe gesture can delete immediately, archive an entry or reveal a secondary action. Immediate removal is easy to understand, but it can be frustrating when a user swipes accidentally. A temporary undo action provides a safer experience without adding another confirmation dialog.

Approach User feedback Data handling Suitable use
Immediate delete Fast and decisive Delete from storage at once Disposable tasks or temporary rows
Snackbar undo Fast with recovery Delay permanent deletion briefly Messages, notes and shopping lists
Archive on swipe Item leaves the main list Change status rather than delete Emails, records and saved content
Confirmation dialog Explicit but slower Delete after approval Financial or legally important records

A Snackbar is a practical choice for most lists. Save the removed object and its original position, then restore it if the user taps Undo. If the app is closed before the Snackbar expires, the deleted item should still have a defined state in the database.

private fun showUndo(task: Task, position: Int) {
    Snackbar.make(recyclerView, "Task removed", Snackbar.LENGTH_LONG)
        .setAction("Undo") {
            adapter.insertAt(position, task)
        }
        .show()
}

For a SQLite-backed application, consider marking the row as deleted first and permanently clearing it after the undo period. This approach is more resilient if the device rotates or the process is recreated. It also prevents a later database reload from bringing back an item that the user expected to be gone.

Improve Visual And Accessible Feedback

The default swipe animation tells users that an item is being dismissed, but a background colour and icon make the result clearer. Override onChildDraw() to paint a red or amber background and draw a delete or archive icon behind the moving row. Red is commonly recognised as destructive, while a neutral archive colour is better when the operation is reversible.

override fun onChildDraw(
    canvas: Canvas,
    recyclerView: RecyclerView,
    viewHolder: RecyclerView.ViewHolder,
    dX: Float,
    dY: Float,
    actionState: Int,
    isCurrentlyActive: Boolean
) {
    val itemView = viewHolder.itemView
    val background = Paint().apply {
        color = Color.rgb(198, 40, 40)
    }

    if (dX < 0) {
        canvas.drawRect(
            itemView.right + dX,
            itemView.top.toFloat(),
            itemView.right.toFloat(),
            itemView.bottom.toFloat(),
            background
        )
    }

    super.onChildDraw(
        canvas, recyclerView, viewHolder,
        dX, dY, actionState, isCurrentlyActive
    )
}

Do not make swipe the only way to remove content. Users who rely on TalkBack, keyboard navigation or switch access may not perform a horizontal gesture. Add a visible overflow action, contextual menu or button, and announce the result with accessible text. A concise message such as “Task removed. Undo available” is more useful than reporting only a visual change.

Test different row heights, long titles and images. A dense list used on smaller phones in Brisbane may behave differently from a tablet layout used at a Perth workplace. Check that a fast swipe, a short partial swipe and a cancelled gesture all produce sensible results.

Test Persistence And Release Behaviour

Test deletion while the device is rotated, when the app returns from the background and after the list is repopulated. Verify that the adapter count, visible rows and stored records agree. Espresso tests can perform a swipe and assert that the expected item disappears, while database tests can confirm that the correct identifier—not merely a screen position—was removed.

Australian developers should also consider privacy expectations when the list contains names, addresses or customer notes. The Privacy Act 1988 and the Australian Privacy Principles make careless retention and disclosure of personal information a serious concern. A swipe labelled “Delete” should have a clear meaning, especially if a record is copied to cloud storage or shared with a service provider.

Use the following implementation practices when preparing the feature:

  • Keep the source list and adapter state synchronised after every dismissal.
  • Use stable database IDs instead of relying on adapter positions for storage operations.
  • Provide Snackbar undo for content that users may remove accidentally.
  • Support a button or menu action for people who cannot swipe.
  • Test both left-to-right and right-to-left layout behaviour.
  • Draw clear background feedback without hiding important row content.
  • Recheck deletion after rotation, process recreation and database reloads.

A swipe-to-dismiss feature is successful when it feels immediate but remains recoverable and understandable. ItemTouchHelper handles the gesture mechanics, while careful data management, accessibility support and persistence determine whether the feature is dependable in a real Android application.