Did you ever feel like the Android Toast as simple and awesome it might be, just lacks some elegance? Well, beautifying it is also simple and we can even use the new Toast with just one like of code in the Android project.
All we have to do is to extend the Toast and use our own custom layout.
Here is what I used for my Toast layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_toast"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_toast"
android:textColor="@color/toast_text"
android:drawablePadding="6dp"
android:gravity="left|center_vertical" />
</LinearLayout>
Most of the beautifying part is done by our simple background bg_toast.xml. Pick your own colors for background and border.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners android:radius="1dp"/>
<solid android:color="@color/toast_background" />
<padding
android:left="8dp"
android:top="8dp"
android:right="8dp"
android:bottom="8dp" />
<stroke
android:width="1dp"
android:color="@color/toast_border" />
</shape>
Here is our class which extends the Toast.
public class MyToast extends Toast {
public MyToast(Context activityContext, String message, int duration) {
super(activityContext);
this.setDuration(duration);
LayoutInflater inflater = (LayoutInflater) activityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast, (ViewGroup) ((Activity) activityContext).findViewById(R.id.toast));
this.setView(view);
TextView tv = (TextView) view.findViewById(R.id.tv_message);
tv.setText(message);
}
}
With all those in place all we have to do is instantiate it from our activity and display it.
MyToast toast = new MyToast(MyActivity.this, message, Toast.LENGTH_LONG); toast.show();
This can be made even better by throwing this in a utility class in a static method and calling the method.
public class MyViewUtil {
public static void showToast(Context activityContext, String message) {
MyToast toast = new MyToast(activityContext, message, Toast.LENGTH_LONG);
toast.show();
}
}
All we need to do from now is to call this method from any activity we want the Toast to be displayed.
MyViewUtil.showToast(MyActivity.this, "Message to display in Toast");
You might have noticed that I have a image drawable in the TextView in our Toast. You may put other stuff but for a Toast anything more than that might be too much. We may have to use a custom Dialog for such stuff. Finally this is how the final Toast looks from the code above.

