Lesson 9: Simple Notifications using the Toast class and example

Android allows you to display a temporary pop-up window that informs the user via a message that appears on the screen for a small amount of time (after a while the window disappears).

This window that overlays the interface that is being displayed at the moment is managed by a class called Toast.

Create a project called Project008.

Issue:

Generate a random number between 1 and 100000. Show the number by a pop-up window for a period of time. Then through an EditText (“Number”) control, ask the operator to enter the number you saw on the screen. When a button is pressed, control the randomly generated number with which the user entered and using another Toast to tell if he was right or not.

The first thing we do is create the following interface:

That is to say that we have a TextView, an EditText (“Number”) and a Button. We set the values “tv1”, “et1” and “button1” as id. Remember that in the “Component Tree” window we have the reference of all the objects that our interface contains.

Now let’s see what the new Toast class is, we have to create an object of the Toast class, for this we call the static makeText method of the Toast class. From the returned object we call the show method.

The makeText method has three parameters: the first refers to the window or Activity where it appears (this), the second is a String that will be displayed and finally is a constant that indicates that the notification will be displayed for a long time or short: