Question

Currently there only exist two duration for a Toast: Toast.LENGTH_SHORT and Toast.LENGTH_LONG...

But what if you want to increase the duration of a Toast in Android?

Here is a hack I came up with and wanted to share:

public void createToast(Context context, String s) {
    int duration = Toast.LENGTH_LONG;
    final Toast toast = Toast.makeText(context, s, duration);

    toast.show();

    new CountDownTimer(5000, 1000) 
    {
        public void onTick(long millisUntilFinished) {
            if (toast.getView().getWindowToken() != null)
                toast.show();
            else
                cancel();
        }
        public void onFinish() {
            if (toast.getView().getWindowToken() !=null)
                toast.show();
            else
                cancel();
        }

    }.start();
}

If you want a longer toast, just increase the duration of the CountDownTimer.

Please make note of the lines

if (toast.getView().getWindowToken !=null)

If the windowToken of the toast is null, that is pretty much saying the Toast has already left the view, (i.e. the toast was canceled).

I found a few solutions online for increasing the duration of a toast, but I couldn't find one to preserve dismissal if the toast has been dismissed by the user. So I pieced the above together to preserve normal Toast functionality.

Let me know what you think!

Was it helpful?

Solution 2

I posted this question a little wonky, what I was really looking to do was to share this following hack with everyone on how to make a Toast duration Longer in Android:

public void createToast(Context context, String s) {
     int duration = Toast.LENGTH_LONG;
     final Toast toast = Toast.makeText(context, s, duration);

     toast.show();

     new CountDownTimer(5000, 1000) 
     {
         public void onTick(long millisUntilFinished) {
             if (toast.getView().getWindowToken() != null)
                 toast.show();
             else
                 cancel();
         }
         public void onFinish() {
             if (toast.getView().getWindowToken() !=null)
                 toast.show();
             else
                 cancel();
         }
     }.start();
}

OTHER TIPS

First of all, I don't see your question. If the question is "what do you think?", I doubt about the cases where you would need a Toast longer than Toast.LENGTH_LONG. If Toast.LENGTH_LONG if short, probably is better to use an AlertDialog.

Anyway, your solution seems a little heavy... you can stack the Toast messages, so you could make two or more Toasts with the same message and instantiate one after the other. The effect of this should be what you are looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top