Toast messages in android are a way to display a info level message such as “Battery low”/”Update successful” to the user. Toasts however do not try to grab the attention of the user by explicitly asking for acknowledgement, meaning,
- they just silently pop-up without blocking the user’s current activity.
- display the required message and disappear.
- the Context ( usually the activity instance),
- the message string or a resource id that refers to the message string, and
- a duration
as arguments and returns a Toast instance. You can then call the show() method to display the toast. Note that if you forget to call the show() method , the message will not be visible on the screen and android does not complain either as its not an error. You can control how long you want to display the toast on the screen by supplying one of the two pre-defined durations, Toast.LENGTH_SHORT
Custom toasts in android
By default, the toast messages appear as a rectangular box as shown above. You can customize the
appearance by providing your own View as argument to the setView(). Instead of using the makeText() method,
- create a new instance of the Toast
- Set the desired view
- Set the duration
- Call show.
Now lets look at the Java code. The useful elements are highlighted for easy reference.
- Inside the onClickListener() for the first button we use the static makeText() method to create a new instance of Toast We then set the duration and call show() on the Toast instance.
- When we use the setContentView() method with a desired layout, android automatically reads the xml layout file, parses it, creates the necessary UI objects in memory and renders them on the screen. Not only is this expensive, but also a very tedious process to do it manually. Luckily we don’t have to because android exposes the LayoutInflater class that is available to all activities via the getLayoutInflater() method. You can use the inflate() method and pass it a resource id and an optional parent container to inflate the view based on a xml layout resource.
- We create an android custom toast message with the inflated view and display it on the screen. We set the duration to Toast.LENGTH_LONG as shown.