How can I show a toast for a specific duration?
Asked Answered
D

12

24

This is the way I have to show the Toast for 500 milliseconds. Though, it's showing more than a second.

Toast.makeText(LiveChat.this, "Typing", 500).show(); 

How can I show Toast only for 500 milliseconds?

Dodgem answered 24/1, 2013 at 14:32 Comment(3)
read the doc. the last parameter can take predefined values only, it is not in millis.Justifiable
You can show the toast as long as requiredBasanite
Possible duplicate of Can an Android Toast be longer than "Toast.LENGTH_LONG"?Coheir
F
70

This cannot be done. To show a toast for a length shorter than Toast.LENGTH_SHORT, you must cancel it after the time you want. Something like:

final Toast toast = Toast.makeText(getApplicationContext(), "This message will disappear in half a second", Toast.LENGTH_SHORT);
    toast.show();

    Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
           @Override
           public void run() {
               toast.cancel(); 
           }
    }, 500);
Forbidden answered 24/1, 2013 at 14:36 Comment(1)
another android api design flawSolitary
C
2

I found this answer. Albeit a bit more complex it also allows you to create toasts longer than Toast.LENGTH_LONG. You might have to change the tick duration from 1000ms to 500ms.

private Toast mToastToShow;
public void showToast(View view) {
   // Set the toast and duration
   int toastDurationInMilliSeconds = 10000;
   mToastToShow = Toast.makeText(this, "Hello world, I am a toast.", Toast.LENGTH_LONG);

   // Set the countdown to display the toast
   CountDownTimer toastCountDown;
   toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) {
      public void onTick(long millisUntilFinished) {
         mToastToShow.show();
      }
      public void onFinish() {
         mToastToShow.cancel();
         }
   };

   // Show the toast and starts the countdown
   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 cancelled 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 cancelled when the countdown is finished.

Capo answered 30/12, 2015 at 16:38 Comment(0)
E
2

Adding to @Senth's answer, if you don't wont to accumulate the time when you call the showToast method multiple times, with the same Message:

private Toast mToastToShow = null;
String messageBeingDisplayed = "";

/**
 * Show Toast message for a specific duration, does not show again if the message is same
 *
 * @param message     The Message to display in toast
 * @param timeInMSecs Time in ms to show the toast
 */
public void showToast(String message, int timeInMSecs) {
    if (mToastToShow != null && message.equals(messageBeingDisplayed)) {
        Log.d("DEBUG", "Not Showing another Toast, Already Displaying");
        return;
    } else {
        Log.d("DEBUG", "Displaying Toast");
    }
    messageBeingDisplayed = message;
    // Set the toast and duration
    int toastDurationInMilliSeconds = timeInMSecs;
    mToastToShow = Toast.makeText(this, message, Toast.LENGTH_LONG);

    // Set the countdown to display the toast
    CountDownTimer toastCountDown;
    toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, timeInMSecs /*Tick duration*/) {
        public void onTick(long millisUntilFinished) {
            if (mToastToShow != null) {
                mToastToShow.show();
            }
        }

        public void onFinish() {
            if (mToastToShow != null) {
                mToastToShow.cancel();
            }
            // Making the Toast null again
            mToastToShow = null;
            // Emptying the message to compare if its the same message being displayed or not
            messageBeingDisplayed = "";
        }
    };

    // Show the toast and starts the countdown
    mToastToShow.show();
    toastCountDown.start();
}

You can display toast now for 500 ms like this:

showToast("Not Allowed", 500);
Eparchy answered 22/2, 2017 at 14:8 Comment(0)
G
1

Can't do what you are asking with the standard Toasts. Perhaps you should think about integrating a 3rd party library that gives you better Toast options (named Crouton). I haven't used it myself, but people seem to like it.

You can't control the length of Toasts in the standard OS.

Crouton link: https://github.com/keyboardsurfer/Crouton

Goudy answered 24/1, 2013 at 14:38 Comment(0)
A
1

This one is working fine for me.

final Toast mToastToShow;
            int toastDurationInMilliSeconds = 10000;
            mToastToShow =  Toast.makeText(getApplicationContext(), "Snapshot Saved Successfully.",Toast.LENGTH_LONG);


            // Set the countdown to display the toast
            CountDownTimer toastCountDown;
            toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) {
                public void onTick(long millisUntilFinished) {
                    mToastToShow.show();
                }
                public void onFinish() {
                    mToastToShow.cancel();
                }
            };

            // Show the toast and starts the countdown
            mToastToShow.show();
            toastCountDown.start();

the countdown is used to display a toast message for a specific duration.

Amathiste answered 17/1, 2017 at 12:39 Comment(0)
P
0

I don't believe this can be done, you can only use Toast.LENGTH_LONG or Toast.LENTH_SHORT you can't define your know speed.

Pallmall answered 24/1, 2013 at 14:35 Comment(0)
P
0

This can't be done. The values of Toast.LENGTH_SHORT and Toast.LENGTH_LONG are 0 and 1. This means they are treated as flags rather than actual durations so I don't think it will be possible to set the duration to anything other than these values.

Patent answered 24/1, 2013 at 14:39 Comment(0)
S
0

Try it first. This sets toast to a specific period in milli-seconds:

public void toast(int millisec, String msg) {
    Handler handler = null;
    final Toast[] toasts = new Toast[1];
    for(int i = 0; i < millisec; i+=2000) {
        toasts[0] = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        toasts[0].show();
        if(handler == null) {
            handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    toasts[0].cancel();
                }
            }, millisec);
        }
    }
}
Showplace answered 26/8, 2015 at 10:29 Comment(2)
adding 2000 to i won't ensure that the time has past.. you need to use clock insteadVassar
you can't count that adding 2000 to i will add 2 seconds, it's depends on the device speed. If you want to loop until time you need to do something like while((System.currentTimeMillis()-startTime)<2000)). That's basic in every programing language.. never different the time base on the loop interval.Vassar
L
0

I tried different method and this method works for me

 final Toast mytoast = Toast.makeText(getApplicationContext(), jsonObject.getString("response_message"), Toast.LENGTH_SHORT);
 mytoast.show();

                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mytoast.cancel();
                            }
                        }, 5000);// 5 sec
Loudermilk answered 6/12, 2017 at 7:28 Comment(0)
G
0

I have created a class ToastMessage in droid side.

   public class ToastMessage: IToast
        {
            public void LongAlert(string message)
            {
                Toast toast = Toast.MakeText(Android.App.Application.Context, message, ToastLength.Short);
                toast.Show();
                Device.StartTimer(TimeSpan.FromSeconds(0.5), () =>
                {               
                   toast.Cancel();
                    return false;
                });
            }
        }

I have created interface IToast

 public  interface IToast
    {
        void LongAlert(string message);
    }

Calling By Dependency Service

 DependencyService.Get<IToast>().LongAlert("Right Answer");
Gwyngwyneth answered 22/5, 2018 at 7:27 Comment(0)
C
0

Accepted answer is correct but in my case the toast blink(show & hide) can be noticed..

I got a solution where Toast is not blinking and you can customise the Toast as well.

Lets begin,

1) Create a class Named LongToast.

class LongToast {

private LongToast() {}

static void makeLongToast(Context context,String text, long durationInMillis) 
{

 final Toast toastMessage = new Toast(context);

 //Creating TextView.
 TextView textView = new TextView(context);

 //Setting up Text Color.
 textView.setTextColor(Color.parseColor("#fafafa"));

 //Setting up Text Size.
 textView.setTextSize(17);

 //Setting up Toast Message Text.
 textView.setText(text);

 //Add padding to Toast message.
 textView.setPadding(20, 20, 20, 23);

 //Add Gravity TextView.
 textView.setGravity(Gravity.CENTER);

 //Adding TextView into Toast.
 toastMessage.setView(textView);

 //Access toast message as View.
 View toastView = toastMessage.getView();

 //Set Custom Background on Toast.
 toastView.setBackgroundResource(R.drawable.test);


 new CountDownTimer(durationInMillis, 1000)
  {
   public void onTick(long millisUntilFinished)
   {
    toastMessage.show();
   }
  public void onFinish()
   {
    toastMessage.cancel();
   }

  }.start();
 }
}

2) Create a drawable xml for customising the Toast.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
 <shape android:shape="rectangle">
 <solid android:color="#009973"/>
 <corners android:radius="20dp" />
 <stroke
  android:width="4dp"
  android:color="#01ffc0"
 />
</shape>

you can customise the toast as per your need.

3) Finally Calling Toast.

LongToast.makeLongToast(this,"whatever you want",10000);//duration in seconds

ref : click here to check

Thanks!!.

Cyndi answered 29/3, 2019 at 10:24 Comment(0)
M
-3
Toast.makeText(LiveChar.this,"Typing",Toast.LENGTH_SHORT);

This is the only way you can..

Menard answered 24/1, 2013 at 14:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.