31

I developed an android application and I am facing a problem with Toast. Suppose I am displaying a Toast, it is displayed on the application window. When a Dialog box is appears, the toast doesn't disappear instantly .

I want to know how I can cancel the toast.

midhunhk
  • 5,560
  • 7
  • 52
  • 83
Dev.Sinto
  • 6,802
  • 8
  • 36
  • 54
  • Backing up what @EboMike [said in his answer](http://stackoverflow.com/a/4395089/383414), I've had success with my `Boast.java` gist for the last few years - [Boast.java on Github](https://gist.github.com/mobiRic/9786993) – Richard Le Mesurier Aug 16 '16 at 20:55

8 Answers8

53

Toast.makeText returns a Toast object. Call cancel() on this object to cancel it.

EboMike
  • 76,846
  • 14
  • 164
  • 167
9

The shortest duration you can specify for the toast is Toast.LENGTH_SHORT which has a value of 0 but is actually 2000 milliseconds long. If you want it shorter than that, then try this:

    final Toast toast = Toast.makeText(ctx, "This message will disappear in 1 second", Toast.LENGTH_SHORT);
    toast.show();

    Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
           @Override
           public void run() {
               toast.cancel(); 
           }
    }, 1000); //specify delay here that is shorter than Toast.LENGTH_SHORT
Trikaldarshiii
  • 11,174
  • 16
  • 67
  • 95
noypiscripter
  • 1,451
  • 1
  • 13
  • 13
4

I think there is no need to create a custom toast.

Create only single instance of the Toast class. We just set the text of the toast using toast.setText("string"), and call toast.cancel() method in onDestroy() method.

Working code snippet as follows:

package co.toast;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ShowToastActivity extends Activity {
    private Toast toast = null;
    Button btnShowToast;

    @SuppressLint("ShowToast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // creates only one toast object..
        toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);

        btnShowToast = (Button) findViewById(R.id.btnShowToast);

        btnShowToast.setOnClickListener(new OnClickListener() {

             @Override
             public void onClick(View v) {

                // only set text to toast object..
                toast.setText("My toast!");
                toast.show();
            }
        });
    }

    @Override
    protected void onDestroy() 
    {
        toast.cancel();
        super.onDestroy();
    }

    @Override
    protected void onStop () {
        super.onStop();
        toast.cancel();
    }
}

Hope this helpful to you..

galath
  • 5,717
  • 10
  • 29
  • 41
Swapnil Sonar
  • 2,232
  • 2
  • 29
  • 42
0

Use cancel method of tost : toast.cancel();

Mahesh
  • 2,862
  • 2
  • 31
  • 41
0

This is a basic example using the cancel() method of a Toast.

Toast mytoast;
mytoast = Toast.makeText(getApplicationContext(), "Hi Ho Jorgesys! ", Toast.LENGTH_LONG);
mytoast.show();
....
....
....
if(CancelToast){
  mytoast.cancel();
}
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
0
Toast toast;

private void showToast(String text) {
    if (toast!=null)
        toast.cancel();
    toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
    toast.show();
}
Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40
0

First you have to create toast object

private Toast toast;

Then create method for Display message as Toast

private void showToast(String text) {
    if (toast != null) toast.cancel(); // cancel previous toast 
    toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
    toast.show();
}

Now Call below method when you have to cancel toast

if (toast != null) {
    toast.cancel();
}

Call below method when you have to display Toast

showToast("Your Message");
Mehul Boghra
  • 202
  • 3
  • 11
  • Should be `private Toast toast = null;` to prevent error message for possibly uninitialized toast. – TJJ Apr 30 '21 at 20:46
-1

Ok, I too am trying to cancel a Toast, and can't seem to get the cancel() call to get invoked in either the Activity.onDestroy() or the Activity.onStop(), etc. After some API-doc reading and googling of others needing help getting Toasts to get cancelled, I'm thinking I'm still not clear on when Activities get stopped, paused, destroyed. I need a sure-fire way to force my activity to get paused or stopped.

In my specific case, since there are only short and long duration Toasts, I decided to iterate a loop 5 times doing a show() of a long-duration toast, so it would stay on-screen for 15-20 seconds. That works fine!

But, the drawback (negative side-effect) of using a Toast object is that they persist even AFTER the user abandons your app and goes back to home-screen and starts using some other app...your toast is gonna live for the next 15-20 seconds, unless you can guarantee that you can find some place (some way) to invoke cancel(). Also, you must believe that Android will honor your call to cancel() !

So, to that end, I've been tweaking my simple loop, trying to invoke cancels right in the loop, and prove to myself it will honor a cancel call, and visually behave as expected.

Code snippet: Note: 'toast' is a public INSTANCE variable, so we have only ONE instance of the Toast-object [ as is recommended above, and which a commenter confirmed was working two years ago, in Activity onStop() and OnDestroy() ]

toast = Toast.makeText(ctxt, result, Toast.LENGTH_LONG);
    for (int i=0; i < 5; i++)
    {
        // Long-toasts each last about 3.5 secs
        toast.show();

        android.os.SystemClock.sleep(1500);
        toast.cancel();
        android.os.SystemClock.sleep(1500);
        toast = Toast.makeText(ctxt, result, Toast.LENGTH_LONG);
    }

Ok, the original loop contained just that one line doing the show. That works, by itself.

But to experiment, I added those next four lines, to sleep for about half way thru the 3.5 second showing, then cancel it, sleep again for a second and a half, and then re-create and show the Toast again.

I expected to see the toast for approx 1.5 secs, then see it disappear, and come back on in another 1.5 secs, etc.

Guess what...the toast never appears AT ALL!

Ok, I'm in total mumble-mode...what am I missing, in understanding the inner-mysteries of how the Toast-class is implemented and is supposed to behave?

And, back to my first issue: How best to get my Activity to go into a paused or stopped state?

[ Note: I READ this forum a LOT...it's great !!! This is my first posting into the middle of a thread-discussion...Sorry that my reply is getting flagged as an ANSWER, rather than as a QUESTION relating to this thread's topic. ]

David
  • 2,253
  • 5
  • 23
  • 29
  • If you have a question, please post a ... [question](http://stackoverflow.com/questions/ask) :-) Note: this is _not_ a forum, implying that there are _no_ discussions! You are supposed to either post questions or answers (or comments for trying to clarify) – kleopatra Aug 30 '15 at 08:09
  • Ok, to answer my own comment: I've decide one should NOT use Toast, especially in a loop to lengthen the duration. The soln for me was to drop using Toast, and implement my own look-alike using just a TextView. That way, the output won't hang around after the app's activity completes. – David Sep 06 '15 at 13:39