Toast is a simple pop-up notification message, that automatically fades away after a certain amount of time. Toasts are used to notify user of a completion of certain operation, for example, if you are working on a task management application, toast can be used to tell your user that a task has been successfully saved.
Toast can be displayed as a simple text message or a more informative and pretty customised view. We will take a look at both ways, and start with a simple one:
Simple Toast View
I will use a button to display our toast, so first thing that we need to do is to add a button element to the app layout:activity_main.xml file:
Now lets go ahead and modify our activity file.
MainActivity.java file:
Explanation:
To display a toast message we are using makeText() and show() methods.
makeText() method requires three parameters to be passed on to it:
- application context
- message text - in our case it is a string "Hello!"
- duration - we've declared this variable in the beginning of the activity class and set its value to duration = Toast.LENGTH_LONG; (line 23) which means that we will show the message for a long period of time. Alternatively this variable value can be set to Toast.LENGTH_SHORT;
Demo
Android Simple Toast Example |
Custom Toast View
To have a prettier toast message displayed in your application you will need to create a customized layout for your toast. To create a customized layout go to the res/layout directory, create a new xml file and paste the following code into it:
As you can see our layout has two elements:
- TextView - to display out toast message text;
- ImgaeView - to display an image;
Important!
On line 3 our layout id is defined, which is required to be able to inflate this layout from XML.
Now (as you've probably guessed already:) we need to modify our activity file.
ActivityMain.java file:
ActivityMain.java file:
Explanation:
line 29 - first we need to retrieve LayoutInflator using getLayoutInflator() method. Then we create a view object and, using LayoutInflator that we have just retrieved, we inflate the layout from XML into a View object;
line 33 - set the value of the TextView;
line 37 - set the location at which the notification should appear;
line 38 - set duration;
lines 39-40 - set the view to show and call show() to display our toast.
Demo
Android Custom Toast Example |
Source Code
http://developer.android.com/guide/topics/ui/notifiers/toasts.html
Toast imgae is taken from here:
http://www.wpclipart.com/food/breads_and_carbs/bread/toast.png.html