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?
In general, a Toast can be displayed for either 2 seconds (Toast. LENGTH_SHORT) or 3.5 seconds (Toast. LENGTH_LONG).
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.
Use the makeText() method, which takes the following parameters: The application Context . The text that should appear to the user. The duration that the toast should remain on the screen.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With