Skip to main content

How to make custom toast in Android with Example

Android Custom Toast With Example

Android Custom Toast With Example

Hello World, today we will be going to see how we can make custom toast and in this tutorial, we will see custom toast with an example. See below as an example.

Android Custom Toast gif

Before starting let's see.

What is Toast? When to use it?

Toast is a view that contains text which notifies the user with some information.

We can use toast when we want to notify the user.

Making Custom Toast with Example

To make custom toast we need to follow certain steps as follows.

Step 1. Create a Custom Layout for Toast

the first step is to make a layout file for our toast.

To make a layout file, right-click on layout folder under res and select new -> layout resource file.

we will name this file as custom_toast.xml and in this file, we will make our layout which will b shown in the toast. Check the below code for the layout file.

In the above code, we set the id to the parent view and we added an imageview and a textview.

We are keeping things simple so that you can understand better.

our layout looks like this below.

Step 2. Set layout file to the Toast

To trigger the toast we made a button in the activity layout and calling the makeToast function on click.

Let's see the code in the makeToast function.

In the above code, when we click the button this function triggers and in the function first we are making an empty toast or initialize the toast and pass the context.

In the next line, we are inflating our custom toast layout using getLayoutInflater() and then calling inflate method which accepts 2 parameters.

The first parameter is out layout file reference and the second parameter is the root view group that is our custom layout parent view so that we find the view by using its id and cast it as ViewGroup. Then we are specifying the toast duration as usual.

Finally, the next step is setting this layout to the custom toast. Using the setView method we are setting the layout to the toast and then show the toast as we do with default toast.

Now run your app and click on the button you will see your custom toast.

Now you can customize your layout file as per your requirement and make your custom toast more beautiful.

If you like this article do share it with your friends and batchmates and don't forget to subscribe to our newsletter if you haven't joined already.

Thanks for reading have a nice day.

Share this Article 👇

Subscribe to our Newsletter

By subscribing to our newsletter you're agreeing with our T&C.

Popular Posts

Customize rating bar in android

Working with Bottom Navigation bar in Android [Full Guide]

Custom Switch in Android | | Android Tutorial