Custom Toast in Android 📧
In this article, I will show you how to create a custom Toast that can have a custom layout. Then we end up with some libraries that help us o create different custom Toast messages like success, error, info Toasts, and Etc.
Create a Custom Text for Toast:
The Toast class uses a TextView
object for showing a message so that if we have access to it, we will be able to change the text as we want. For getting that TextView
object, I use the getView()
method of Toast class and as it is a non-static method, we can call it by a Toast object as below:
Now by calling methods for the TextView
, we can make it custom:
And our custom Toast will be looking like this:
We can also change the view’s background to red color and the position of the Toast as the below snippet code:
And the custom Toast will be changing like this:
Create a Custom Layout for Toast:
For this approach, we need to design our custom layout for Toast as per below:
And then we are just going to inflate the layout of our whole container views which will be set as the view for that custom Toast:
Let’s see how does it look like 🤩:
Now let’s have a look at the libraries which help us to have a custom Toast as well:
On top of those dependencies, it is the Toasty library which is very easy to use and supports the +14 API level.
And the second one which I recommend is the StyleableToast library. With this one, you can style your toasts either by code or with a style in styles.xml
and it supports +16 API level.
I hope this article was useful to create a custom Toast. Feel free to comment and share it with others 🙌🏽.