Practical undo and redo for Android apps
Undo and redo in an Android app should restore an earlier edit, not replay a navigation event. A user may rename a project, change a form value, remove a list item or reorder notes, and each action needs a predictable way back. Treating these operations as reversible commands provides one history model that works across screens.
Visible state must remain separate from the history that changes it. A command records enough information to undo and redo an action, while a state holder applies the result and publishes it to the interface. This avoids tangled back stacks, duplicate database writes and inconsistent controls when an activity is recreated after rotation.
Android devices from Samsung, Google Pixel and Motorola are common in Australia, and phones are often used one-handed on trains and buses across Sydney, Melbourne and Brisbane. Undo controls and feedback therefore need to remain reachable and legible instead of depending on obscure gestures.
Why edit history is separate from navigation
Android’s back stack normally represents navigation. It does not indicate that deleting a note should be reversible, and clearing the stack may discard a screen without reversing its data change. Navigation history and edit history should therefore be managed independently.
Use the command pattern for reversible operations. Each command can carry a label, an optional payload and the logic required to move the model to its previous or next state. History can also retain personal information, so an Australian app handling covered personal information must protect it under the Privacy Act 1988 and Australian Privacy Principle 11. Avoid storing card details, authentication secrets or sensitive identifiers in an undo payload, and clear history when the user logs out.
Model changes as reversible commands
Start with an explicit model rather than reading and writing views. A minimal implementation can store the before-and-after values for each edit, together with the action label used in feedback.
data class TextDelta(
val before: String,
val after: String,
val label: String
)
class EditHistory {
private val undoStack = ArrayDeque<TextDelta>()
private val redoStack = ArrayDeque<TextDelta>()
fun record(before: String, after: String, label: String) {
if (before == after) return
undoStack.addLast(TextDelta(before, after, label))
redoStack.clear()
}
fun undo(): String? {
val delta = undoStack.removeLastOrNull() ?: return null
redoStack.addLast(delta)
return delta.before
}
fun redo(): String? {
val delta = redoStack.removeLastOrNull() ?: return null
undoStack.addLast(delta)
return delta.after
}
}
Calling undo moves a delta from the undo stack to the redo stack and returns the previous value; redo performs the reverse. A newly recorded edit clears the redo stack because it creates a different branch. For text input, coalesce adjacent edits within a short interval when appropriate instead of recording every keystroke separately.
Keep the interface and history synchronised
Keep the history in a ViewModel or another retained state holder, and expose the current content through StateFlow or LiveData. The activity observes that state and renders it. Undo must update the model first, after which the controls and widgets follow, preventing two sources of truth from drifting apart.
For an Android editor, the practical trade-offs are:
| Concern | Snapshot stack | Command objects |
|---|---|---|
| Memory use | Can grow quickly with full copies | Usually smaller with targeted payloads |
| Persistence | Straightforward but bulky | Requires defined serialisation |
| New branches | Easy to snapshot | Built into command execution |
| User feedback | Needs a separate action label | Label can travel with the command |
After undoing a list change, update the adapter with a proper diff so items do not flicker or lose their selection. Restore the scroll position only when the user expects it. A Snackbar can name the affected action, such as “Message moved to trash”, without exposing internal command names.
Survive lifecycle and data changes
Activities and fragments can disappear while the app remains in the background, so process death must be considered. Save the current document in saved instance state for small values, or persist larger content in Room or SQLite. Keep the history bounded and attach a revision number to each entry so stale commands can be rejected.
A database-backed feature should update the source and write its history record in one transaction. If a command refers to revision 12 but the current row is revision 14, discard it or rebuild the history from the current state. SharedPreferences works for a small preference snapshot, but it is unsuitable for an unlimited command journal.
Sensitive history needs the same protection as the original record. Apply Australian privacy requirements to cached edits, use app-private storage and encryption where risk warrants it, and remove expired entries automatically. Clear consumer disclosures should also remain truthful under the Australian Consumer Law, including whether deleted information can be restored.
Make undo controls clear and reachable
Put undo and redo in a toolbar, overflow menu or accessible keyboard shortcut, with visible enabled and disabled states. Supply content descriptions, tooltips and stable touch targets. On devices with a physical keyboard, Ctrl+Z and Ctrl+Shift+Z provide familiar editing shortcuts.
For a reversible delete, update the interface immediately and show a Snackbar with an Undo action. Keep the action available long enough for someone checking directions on a crowded platform, and never rely on colour alone to show whether redo is available. Screen readers should announce the restored state and any remaining available action.
Good feedback explains what happened. For broader guidance on message formatting, apply the same clarity to action labels and system messages. Use Australian English, Australian date formats and concise wording so users can quickly decide whether to reverse an operation.
Support dialogs lists and forms
Dialogs need explicit semantics. Cancel means abandoning an unfinished dialog, while Undo reverses a completed action. A delete confirmation can perform the deletion and then offer Undo in a Snackbar, but the dialog should not suggest that cancellation will restore something. Form validation errors are not edit commands.
ListViews and RecyclerViews need stable identities so undo can locate the affected item. Commands should cover rename, delete, reorder and selection changes, while the adapter applies the resulting list through a diff. For shared settings, a preference command can capture the previous value and write the restored value through the same repository.
Use restrained animations to show a move or restoration, but avoid animating both the command and the adapter as separate changes. Respect Android’s reduced-motion settings and prevent rapid state updates from hiding one another. The final interface should match the model exactly, including selection and keyboard focus.
Test the history before release
Test the history as a state machine rather than as isolated button presses. Cover repeated undo, redo after an intervening edit, empty stacks, rapid input, rotation, process recreation, database conflicts and logout. Property-based tests can generate random action sequences and verify that undo and redo reach the expected states.
A practical release checklist includes:
- Cap history length and command-processing time.
- Coalesce text edits without merging unrelated actions.
- Make toolbar and Snackbar actions accessible.
- Persist history only when recovery justifies storage.
- Remove sensitive payloads and expired history promptly.
- Exercise lifecycle, concurrency and database failure cases.
Run each scenario across several Android versions and on screen sizes common in the Australian market. Track memory consumption and command latency, and encode expected behaviour in instrumentation tests. A release-ready implementation leaves content, controls and persistent data consistent after every valid history transition.