Use Toast to display warning message in Android

By xngo on February 28, 2019

Overview

Toast is a handy little popup that appears on top of your screen for a limited time. It doesn't interfere with the screen. Therefore, the screen remains visible and interactive. I use it in my Android application iTransit to tell users to upgrade to new bus & metro time schedules. Here in Montreal, bus & metro time schedule change seasonally.

Avoid using it too much. Thinking that this is a good way to provide feedbacks is a bad idea. If your application requires constant feedbacks to your users, then your application is not intuitive. Remember, mobile application is supposed to be simple!

Using Toast

It is easy to use Toast. Simply add your message, set the display time and position your Toast on the screen using Gravity parameter.

If you want to center your text message within the Toast, then you have to center the TextView that is inside the Toast.

Examples on how to use Toast

// 1-liner to display message. Sometimes useful for debugging purposes.
Toast.makeText(getApplicationContext(),
        "Upgrade this app to get more accurate time schedule.", Toast.LENGTH_LONG).show();
 
 
// Set Toast popup in the center of screen.
Toast toast = Toast.makeText(getApplicationContext(),
        "Upgrade this app to get more accurate time schedule.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
 
 
// Re-use message TextView in Toast as it has nice decoration and animation.
String warningMsg="Upgrade this app to get more accurate time schedule.";
Toast toast = Toast.makeText(this, warningMsg, Toast.LENGTH_SHORT);
TextView msgView = (TextView) toast.getView().findViewById(android.R.id.message);
if( msgView != null)
    msgView.setGravity(Gravity.CENTER);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
 
 
// Create your own custom TextView and assign it to Toast.
String warningMsg="Upgrade this app to get more accurate time schedule.";
TextView textView = new TextView(getApplicationContext());
textView.setText(warningMsg);
textView.setTextColor(Color.BLACK);
textView.setBackgroundColor(Color.parseColor("#DDAAAA"));
textView.setGravity(Gravity.CENTER);
 
Toast warningToast = new Toast(getApplicationContext());
warningToast.setGravity(Gravity.CENTER, 0, 0);
warningToast.setDuration(Toast.LENGTH_LONG);
warningToast.setView(textView);
warningToast.show();

Toast screenshot example 1 Toast screenshot example 2 Toast screenshot example 3

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.