What do you want for beakfast ? Just toasts...

Written by Xavier Gouchet - 24 february 2012 - no comments

Toasts ?

Toasts are the usual way to give feedbacks to the user without impacting his experience. The message pops, without having to click on a button to close it.

Usually, a toast can be created using a single line, looking a bit like this, either using a string or with a string resource id (which is better if you want localization).

Toast.makeText(context, "Hello toasts", Toast.LENGTH_SHORT).show();
Toast.makeText(context, R.string.hello_toasts, Toast.LENGTH_SHORT).show();

Android toast with default layout

Custom Toasts

Android also provides a way to have a completely custom view instead, and have all you want, text, images, etc...

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout, null);

// here customize the content of the layout

Toast toast = new Toast(context);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

Android toast with custom layout

Anything else ?

Both methods are quite straightforward, but the second method requires a lot of work. And when you only want to change a tiny details in the default toast, for example the text color, how can you do ?

The idea is to get the TextView created by the default Toast and edit its parameters, like this

Toast toast = Toast.makeText(this, resId, Toast.LENGTH_SHORT);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);


Android toast with customized default layout

More ...

You can find more information on toasts in the Android documentation.

Write a comment

Enter image code :