How To Display Toast Message in Android

What is a Toast Message?

In Android, toast message displays information to users in a short period of time. Usually, toast messages displays at the bottom of the screen. It helps to let users know what happened or what is happening.

How To Display Toast Message In Android?

Displaying a toast message is actually very easy in Android. Commonly, toast messages pop up when user interacts or clicks something on the application. It is very useful to let the user know what is the status of the app. Important note, Still, if your app targets Android 12 (API level 31) or higher, its toast is limited to two lines of text and shows the application icon next to the text. Be aware that the line length of this text varies by screen size, so it’s good to make the text as short as possible.

I will now show you how we can display a toast message in Android. If you are new in creating a toast message, you will have to import packages to be able to use it. After importing packages, you can now make a toast message. To display a toast message, you will use the method makeText() which will have 3 parameters. Firstly, the application context. Secondly, the text or the message that should be displayed. Lastly, the duration of the toast message. Now to display the toast message, we need to add show() method at the end. See the example below then.

Toast toast = Toast.makeText(context, text, duration);;

//you can also chain the method for lesser lines
Toast.makeText(context, text, duration).show(); 

Now that we know how to create a toast message, I’ll show you an example on how to use it.

Toast toast = Toast.makeText(this, "This is a toast message", Toast.LENGTH_LONG);;

Toast.makeText(this, "This is a toast message", Toast.LENGTH_SHORT).show(); 

The context that you will put may vary from the layout you use or from where you are calling the toast message. On the example above, I used the this keyword because it is an activity layout. However, the compiler may also suggest that I use something like Main.this or whatever my activity name is. In regard to using fragment, you should use the getContext method for the context parameter.

That’s it for today’s blog, I hope you learned something. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *