In this blog, we will learn about changing Toast Display in your android application.
We all know displaying Toasts in your android application is quite a useful and powerful way of improving your application’s user experience.
But, while using toast, we usually assume that the view cannot be changed and the view provided or displayed is the only way the toast will appear in our application or we try to use some library project to display colorful toasts.
Changing the look and feel of a toast is super easy and is not that much of code as we think or see in library projects.
So, without wasting any time further, let’s see what we need to do.
APPROACH :
- You need to create an instance of the Toast class through Toast.makeText() function.
- If you need to change the position of the Toast on the Screen then you need to set the gravity by using setGravity() function.
- If you need to change the background of the Toast then you need to use getView().setBackground() function.
- If You need to change the color of the view created then you need to use getView().getBackground().setColorFilter() function.
- If you need to add some icon along with the message in the toast view then you need to first get an instance of the TextView in the toast using getView().findViewById(android.R.id.message) and then use setCompoundDrawablesWithIntrinsicBounds() function.
With these changes, you can change almost all the elements of the Toast as per your use case.
Let’s now look at the code you need to do.
CODE :
1 2 3 4 5 6 7 |
String textToDispalyInToast = "This a customized Toast";// Replace with your own text Toast toast = Toast.makeText(this,textToDispalyInToast , Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP|Gravity.START,toast.getXOffset(),toast.getYOffset());// Add This line and change the gravity Flags used as per your use toast.getView().setBackground(getResources().getDrawable(R.drawable.your_drawable_id));// Replace with your drawable toast.getView().getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);// Replace BLACK with your own color ((TextView)toast.getView().findViewById(android.R.id.message)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.your_icon),null,null,null); toast.show(); |
And with these changes you have changed the whole Toast Display as per your use.
Keep coding and Keep Sharing 🙂