Intro
Toasts are the preferred Android mechanism to deliver short messages to users. But, they tend to be kind of boring. So, why not make them more exciting? Let’s build a custom toast and make it pop!
Custom Layout
First thing we’ll need is a custom layout for amazing toast. Let’s start off with something simple, a TextView and an ImageView:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#DAAA" android:gravity="center" android:orientation="horizontal" android:padding="10dp"> <TextView android:id="@+id/toastTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="#ffffff" android:textStyle="bold"/> <ImageView android:id="@+id/toastButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:background="@null" android:clickable="true" android:src="@mipmap/ic_launcher"/> </LinearLayout> |
Custom Toast
Awesome, we’ve defined our Toast’s layout. Time to use it.
First thing we’ll need to do is inflate it and initialize its views:
1 2 3 |
View rootLayout = activity.getLayoutInflater().inflate(R.layout.view_toast, null); ((TextView) rootLayout.findViewById(R.id.toastTextView)).setText(message); |
Next, we’ll create a new toast and add our custom view to it:
1 2 3 4 |
Toast toast = new Toast(activity); toast.setDuration(Toast.LENGTH_LONG); toast.setView(rootLayout); toast.show(); |
We can customize it even further: to make things interesting, we can also define the Toast’s gravity – to control where it appears on the screen:
1 |
toast.setGravity(gravity, xOffset, yOffset); |
And we’re done, simple as that! This is what the final thing looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private void showToastWithImage(String message, int gravity, int xOffset, int yOffset, Activity activity) { View rootLayout = activity.getLayoutInflater().inflate(R.layout.view_toast, null); ((TextView) rootLayout.findViewById(R.id.toastTextView)).setText(message); Toast toast = new Toast(activity); toast.setDuration(Toast.LENGTH_LONG); toast.setView(rootLayout); toast.setGravity(gravity, xOffset, yOffset); toast.show(); } |
And just call it with:
1 |
showToastWithImage("This is a center Toast", Gravity.CENTER, 0, 0, MainActivity.this); |
Get the full source code here.