TODO app — Delete multiple items with undo timer.

We will work on the same android architecture component app. You can get the code from here.

As of now, the app is able to record todos and mark them as complete. We will add one more piece of functionality, deletion. But not just any delete feature, we want users to have some time to undo their request before we delete it.

We will add the following features to the application.

  • User can can inline delete a task.
  • When the user clicks the delete button, they should see a countdown on the item from 3 to 0, along with an inline undo option.
  • Hitting the undo option should cancel the timer and leave the item as is.
  • If the timer reaches 0, the item will then be deleted.

We will use android’s Countdown Timer for this. We need to create a timer instance in the view holder and manipulate it based on the delete state of the task.

The view holder class will look like this

Let’s edit the layout file. We need to add the delete button on each row and also an undo button and some way to display the timer.

We will use progress bar to display the 3 seconds timer and a normal Button for the undo button.

Instead of a delete button in each row we can also add swipe the row to delete functionality. But that’s not the part of this post. It can certainly be easy to implement with this code.

The layout for task_item.xml will be changed like this.

To make the progress bar circular with progress we need to add progress drawable.

create file drawable/circular_progress_bar.xml

And a circle shape drawable/circle_shape.xml as a background of the progress bar.

Add the static const for the timer duration.

Now, back to the Recycler view adapter. Let’s add handle the delete button click and the undo action.

The onBindHolder(…) method will be like this

We will need to add the isTicking boolean variable because calling timer.cancel() won’t prevent a onFinish() call on timer finished. Event after calling the cancel function the timer will still go in the onFinish() block. To prevent that we will add the isTicking variable.

Let’s also add some helper extension functions to show or hide views based on the state.

And finally add the function in view model which will actually delete the task.

The final app should look like this:

Demo of the application.
Demo of the application.