Android Custom Toast Tutorial

Moving ahead from Simple Toast Example. Here we are going to see about how to display a textview in toast using setView() & some more properties of Toast.
Toast is used to display a short message or notification in quick time without any button ( like OK, Cancel ).

Simple Toast
To display a simple toast, we need to maKeText for that toast & then call show() to display it.
To use makeText(), we need to send 3 arguments.
1) Context
2) Text to display in toast
3) Duration How much time its need to be show
At last call show() to display toast.

[sourcecode language="java"]
/** A Simple Toast displaying "Toast Example - AndroidPeople.com".
* Display duration is short.
* Show() is used to show the toast.
* Toast will automatically close the dialog. */
Toast.makeText(this, "Toast Example - AndroidPeople.com", Toast.LENGTH_SHORT).show();
[/sourcecode]

Toast setDuration()
setDuration(int) is used to set display duration of a toast. You need to set duration in int type.
Toast have 2 default integers for duration
1) Toast.LENGTH_SHORT - Display the toast for short time. Used when the notification text is small.
2) Toast.LENGTH_LONG - Display the toast for long time. Used when the notification text is big.

Custom Toast Notification
Custom toast notification is used when we need to display a custom View as toast by using setView().
create a toast and set any view to display in setView().
Here we created a textview with some UI design to display in toast.

[sourcecode language="java"]
/** Creating TextView to display in toast.
* set Background Color, Text Color, Padding & Text for TextView. */
TextView textView = new TextView(this);
textView.setBackgroundColor(Color.GRAY);
textView.setTextColor(Color.BLUE);
textView.setPadding(10,10,10,10);
textView.setText("Textview as Toast");

/** Create a Toast to display a View.
* Here we are going to display a TextView.
* Toast setView() is used to display a View.
* Toast Display Duration is Long. So it will display for long time.
* Toast setGravity() is used to set position to display the toast. */
Toast toastView = new Toast(this);
toastView.setView(textView);
toastView.setDuration(Toast.LENGTH_LONG);
toastView.setGravity(Gravity.CENTER, 0,0);
toastView.show();
[/sourcecode]

Toast setView()
Used to display a view in toast. we can create a view with our won UI & then set it to setView() to display in view.

Toast cancel()
cancel() is used to stop displaying the toast if the toast is displaying.

Toast setGravity()
setGravity() is used to set position to display the toast.

You can download the full source code from here

Comments

Hi Sash, You can do it. Using

Hi Sash,
You can do it. Using your rounded rectangle BG you can design your toast.

Yup you can use ArrayMap,

Yup you can use ArrayMap, HashMap to store item data..