In the Android SDK, an android.widget.Toast
is a small message that pops up at the bottom of the screen to display an information. The toast will disappear by itself after a specified duration. Here is an example of what a toast looks like and how to display one:
Context context = getApplicationContext();
Toast.makeText(context, "Hello world, I am a toast.", Toast.LENGTH_SHORT).show();
The duration for which a toast is displayed on screen is unfortunately defined by a flag: you can either show it for a SHORT duration, which is 2 seconds or a LONG duration which is 3,5 seconds. But what if you have a long error message that needs to be shown for longer than that? Or if you need to show a countdown that updates every second?
There is no way to directly change the duration for which the toast is shown using the show()
method without reimplementing the whole Toast
class in your application, but there is a workaround. You can use a android.os.CountDownTimer
to count down the time for which to display a toast. The CountDownTimer
class schedules a countdown for a time in milliseconds with notifications at specified intervals until the countdown is finished.
In this example, the countdown is used to display a toast message for a specific duration when a button is pressed:
private Toast mToastToShow;
public void showToast(View view) {
int toastDurationInMilliSeconds = 10000;
mToastToShow = Toast.makeText(this, "Hello world, I am a toast.", Toast.LENGTH_LONG);
CountDownTimer toastCountDown;
toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 ) {
public void onTick(long millisUntilFinished) {
mToastToShow.show();
}
public void onFinish() {
mToastToShow.cancel();
}
};
mToastToShow.show();
toastCountDown.start();
}
Here is how it works: the countdown has a notification time shorter than the duration for which the toast is displayed according to the flag, so the toast can be shown again if the countdown is not finished. If the toast is shown again while it is still on screen, it will stay there for the whole duration without blinking. When the countdown is finished, the toast is canceled to hide it even if its display duration is not over.
This works even if the toast must be shown for a duration shorter than the default duration: the first toast displayed will simply be canceled when the countdown is finished.