Android Toasts

Android toasts are small popup messages used to show small data for a particular period of time. We can set the delay on how much time it should show.

Toasts draws on top of every other views which makes it convenient to show important messages. We can also customize the appearance and position of the toast.

Most topics related to toasts are covered in this article but if you have any queries related to toast you can ask in the comments below.

So lets dive into the tutorial.

Steps included :

  1. Create simple project .

  2. Create layout design to show toast on button click.

  3. Show different types of toast like custom toasts.

1. Create project

If you already have a project created skip this step and follow step 2.

To create project simply navigate file => New => New Project

Then provide necessary details to create project like Project name, package name(this is very important),supported API level. Also make sure that use androidx artifactis is enabled. In most cases, it will be enabled by default. Also set language to java because we are using java for this tutorial. If you are comfortable with kotlin go for it.

Click Finish to build the project.

2. Create layout design

Open activity_main.xml located under res => layout. Open design tab at the bottom. Now drag and drop three buttons from the widget palette. We will show three different toasts using this buttons.

Full layout code

We also need to create another xml file to show custom toast. For that, right click on the layout folder New => Layout resource file. And name it cutom_toast.xml.

Code for custom_toast.xml

3. Show the toast!

3.1. Initialize Views

Now we have created all the layout files, lets move to the logic part where actual code used to create toast.

First lets get reference to the buttons used in the layout. We will implement click action later.

3.2. Implement click action

download full source code here

Last updated