Implementing drag and drop with RecyclerView
RecyclerView is the usual Android home for a long, scrollable collection, but it does not move rows by itself. A drag gesture must update the visible order, the adapter’s backing list and, where needed, persistent storage without making the list jump. ItemTouchHelper supplies the gesture callbacks; the surrounding code decides what may move and how that order survives rotation or process death.
The implementation below uses a drag handle, stable item IDs and one mutable list shared with the adapter. That pattern suits playlists, delivery stops, study tasks and admin queues. It also reflects the Australian market, where the same app may run on a premium handset bought through JB Hi-Fi and on an entry-level Android handset supplied with a Telstra, Optus or Vodafone mobile plan.
Prepare the adapter and data source
Use one source of truth for the order. Give every record a stable ID, keep the mutable list in the fragment or ViewModel, and pass that same instance to the adapter. A small model and backing list might look like this:
data class TaskItem(val id: Long, val title: String)
private val items = mutableListOf(
TaskItem(1, "Pack the charger"),
TaskItem(2, "Book the bus"),
TaskItem(3, "Charge the phone")
)
private lateinit var adapter: TaskAdapter
Create the adapter with this exact list and assign it to the RecyclerView. Keep the adapter small: onCreateViewHolder inflates the row, while onBindViewHolder displays the title and drag handle. Avoid a second copied list, because moving an item in one copy but notifying the other causes duplicate or skipped rows. Keep the list in a ViewModel when it must survive rotation.
Move items with ItemTouchHelper
ItemTouchHelper handles drag directions and swipe actions. Configure only vertical drag flags here, because horizontal swipes are often reserved for delete, archive or share actions elsewhere in the row.
private inner class DragCallback : ItemTouchHelper.SimpleCallback(
ItemTouchHelper.UP or ItemTouchHelper.DOWN,
0
) {
override fun isLongPressDragEnabled() = false
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
val from = viewHolder.bindingAdapterPosition
val to = target.bindingAdapterPosition
if (from == RecyclerView.NO_POSITION || to == RecyclerView.NO_POSITION) {
return false
}
items.add(to, items.removeAt(from))
adapter.notifyItemMoved(from, to)
return true
}
override fun onSwiped(
viewHolder: RecyclerView.ViewHolder,
direction: Int
) = Unit
}
Create the helper from that callback and attach it to the RecyclerView. The move callback changes the backing list and calls notifyItemMoved so RecyclerView can animate the transition. Returning false for an invalid position prevents a stale ViewHolder from corrupting the order.
Start the drag from a clear control
A visible handle gives the user a predictable entry point and avoids stealing ordinary scroll gestures. Attach the helper, pass it to the adapter, and bind the handle’s touch listener to its current ViewHolder:
val itemTouchHelper = ItemTouchHelper(DragCallback())
itemTouchHelper.attachToRecyclerView(recyclerView)
adapter = TaskAdapter(items, itemTouchHelper)
recyclerView.adapter = adapter
holder.itemView.findViewById<View>(R.id.drag_handle)
.setOnTouchListener { _, event ->
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
itemTouchHelper.startDrag(holder)
}
false
}
Give the handle a touch target of at least 48dp and a useful content description. ItemTouchHelper also supplies edge auto-scroll while a row is near the top or bottom. If long-press dragging suits the design better, remove the override of isLongPressDragEnabled and return true. On a crowded Melbourne tram or Sydney train, a dedicated handle is easier to use one-handed than a long press that can be confused with scrolling.
Keep ordering stable and meaningful
Positions are not identities. After a move, notifyItemMoved preserves the animation, while stable IDs let RecyclerView track the same task across rebinds. Enable stable IDs in the adapter:
init {
setHasStableIds(true)
}
override fun getItemId(position: Int): Long = items[position].id
Do not call notifyDataSetChanged after every move: it cancels the animation and can make the row appear to jump. Persist the final sequence of IDs when the drag finishes, preferably from clearView, instead of writing to a database for every intermediate move. When rank is part of the interface, mobile tournament rankings show how a visible position can clarify that relationship, a pattern that also suits delivery stops or revision priorities.
Build and test checklist
Use separate checks for implementation details and device coverage so no drag-specific edge case slips into a release build.
Implementation checks
- Confirm that the adapter and callback modify the same mutable list.
- Keep stable IDs unchanged and call
notifyItemMovedfor each move. - Restrict drag directions and disable unwanted swipe actions.
- Save the ordered IDs after the final drop.
Device checks
- Test portrait, landscape and process recreation.
- Exercise TalkBack, switch access and keyboard navigation.
- Try short labels, long labels and rapid consecutive moves.
- Run the flow on lower-powered Android handsets sold by Australian carriers.
Performance matters beyond flagship phones: check frame timing on slower devices and keep image loading off the UI thread during a drag. In regional areas around Perth and Darwin, developers may first spot dropped frames while testing over patchy mobile data; profiling on the actual handset is more reliable than an emulator. Australian developers commonly call this connection “mobile data”, so keep logs and error messages consistent with that wording.
Handle restoration, accessibility, and protected actions
Drag-only controls can be difficult for people who cannot perform a precise touch drag. Add “Move up” and “Move down” accessibility actions, expose the same commands through a context menu, and announce the item name and new position. A keyboard or switch-access user should be able to complete the same task without relying on the handle’s drag gesture.
Save ordered IDs rather than adapter positions. After process death, rebuild the list from local storage, restore the saved sequence and then reconcile it with the server. Room, DataStore or SavedStateHandle can each serve a different part of that workflow, depending on whether the order is authoritative, a small local preference or transient UI state.
For an administrator-only queue, verify the user before enabling reordering or committing a sensitive order change. The fingerprint authentication pattern demonstrates how an Android app can gate a privileged action behind a biometric check. Keep that verification separate from the drag callback, and require a fresh authentication for destructive or high-impact changes.