See how to create basic toast messages and display them to the user, along with how to position them on the screen, and how to control the duration for which they appear.
- [Teacher] In this exercise, we'll see how to display a simple Toast message and control some simple Toast settings. In Android Studio, let's open the Start Project. And let's open the... Toastactivity file. And let's also open the Toastactivity layout, under the Res folder in the layout and we'll open up the Activity_Toast.
This layout just contains a button to trigger the Toast message along with some controls that will affect how long it will be displayed. Now, in the Toastactivity code, I've already added some user interface logic to connect the controls with some variables that we'll use and an event handler for the button. So in that event handler, let's write the code to display the Toast message. Now for the first example, our code will just show a simple Toast message.
So down here in the Show Toast function, I have some code that checks the radio buttons to see how long the duration should be. To actually show the Toast, let's write the code. Alright, so that's all there is to it to make a simple Toast message. Let's run the app and try it out. So I'll bring the app up in the emulator and I've created an emulator here, so I'll click OK.
Alright, so once the app is running, I'll go ahead and start the Toast Activity and I'll click on the Show Toast button. And you can see that the Toast appears in its default location near the bottom of the screen and then fades after a few seconds. If I change the duration to long, click the button again, you can see that the Toast hangs around for a bit longer this time and then eventually fades out. Now, we can change the Toast's position by adding a call to setGravity. So let's go ahead and do that.
Passing zero offsets, so that it's exactly in the center. I'll save and I'll click the debug again. So now, when we click the Show Toast button, you can see that the Toast has moved to the center of the screen. So that should give you an idea of how easy it is to create and display Toast messages. In the next example, we'll create a more customized Toast message.
- Communicating with toasts
- Displaying a snackbar
- Using snackbars with actions
- Creating simple dialogs and choice dialogs
- Returning results from a dialog
- Creating custom dialogs
- Displaying notifications
- Using NotificationCompat
- Working with expanded notifications