Toasts
Toasts have been available for developers to use in their Android apps for a long time. The simplest form of pop-up message, they are unobtrusive and short-lived, wrap around their content and display at the bottom of the screen.
You may choose a Snackbar over a Toast if you need an action alongside the message or to ensure the app displays the message in the same UI where the action occurred.
The sample project contains a Copy list button, which saves the list of fruits with their quantities to the clipboard on the device. You can show a simple Toast to confirm to the user that the app successfully saved the content.
In the project, open MainActivity.kt. The button with ID button_copy
already has a click listener, which calls saveToClipboard()
. This method handles saving the text to the clipboard, then calls showToast()
. Here, you’ll add code to display the Toast.
Add the following code:
Toast.makeText(this, R.string.toast_copied_to_clipboard, Toast.LENGTH_LONG).show()
This creates a Toast with the provided string to display and how long to show it.
Build and run. Tap Copy list, and you’ll see the Toast appear at the bottom of the screen.
Where to Go From Here?
Download the final project by clicking Download Materials at the top or bottom of this tutorial.
You’ve now learned some of the different ways you can provide useful alerts and hints to improve users’ experience of your app.
If you want to keep experimenting, there are many areas for additional customization. For example, you could try changing the theme of your Snackbar to change the look and feel of your app. The Material Components documentation has a lot of advice on theming. Or you could try adding your own custom touch responses and loading indicators using animations. Start with the Google guide for some inspiration.
There is more to learn about dialogs too. Why not try adding the MaterialTimePicker or MaterialDatePicker to your app to see how they work. You could also try creating another custom dialog with a more complex layout.
Hopefully, you’ve learned a lot and had some fun on the way. If you have any comments or questions, please join the forum discussion below.