How to customize Toasts

SDK Version: 

Customizing Toasts

A toast notification is a message that pops up on the surface of the window. It only fills the amount of space required for the message and the user's current activity remains visible and interactive. The notification automatically fades in and out, and does not accept interaction events.

The Basics

You can create customized Toasts and setting its display position, as you like.
Here's a little code snippet to demonstrate how it works:

  1.        String text = “example toast text!;
  2.        Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
  3.        /* Positioning your Toast */
  4.        int offsetX = 0, offsetY = 0;
  5.        toast.setGravity(Gravity.BOTTOM, offsetX, offsetY);

Creating a Custom Toast View

If a simple text message isn't enough, you can create a customized layout for your toast notification. We are going to use custom view to create a fancy Toast. You could also use your own layout.
The Toast's setView method's going to do the job for us.

  1.                  Context context = getApplicationContext();
  2.                  String text = new String("Customized Toast!");
  3.                  Toast customizedToast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
  4.                  customizedToast.setGravity(Gravity.TOP, 0, 0);
  5.                  LinearLayout mLayout = new LinearLayout(context);
  6.                  mLayout.setOrientation(LinearLayout.VERTICAL);
  7.                  TextView mTV = new TextView(context);
  8.                  CustomView cv = new CustomView(context);
  9.                  mTV.setText(text);
  10.                  int height = LinearLayout.LayoutParams.FILL_PARENT;
  11.                  int width = LinearLayout.LayoutParams.WRAP_CONTENT;
  12.                  mLayout.addView(cv, new LinearLayout.LayoutParams(height, width));
  13.                  mLayout.addView(mTV, new LinearLayout.LayoutParams(height, width));
  14.                  customizedToast.setView(mLayout);
  15.        ;

Hope you found it useful, feel free to ask!