Question

I am using toast on android, However I dont want the toast to disappear. but rather stay... And I dont want the toast to show up on different activity or fragment. If I called toast in certain fragment, i dont want it to be seen in a different fragment or activity. Lets say activity 1, i call toast..i go to activity 2... i dont want toast to be displayed yet. when i return to activity 1 i see the toast still in place. I also want this for fragments.

Toast toast = Toast.makeText(dialog.getContext(),R.string.serverError, Toast.LENGTH_LONG); toast.show();

Was it helpful?

Solution 3

One possibility is to make the Toast global in your Fragment/Activity. Now you can call Toast.cancel() in a callback like onPause(), which is called if you switch an Activity or Fragment.

The docs say about cancel:

Close the view if it's showing, or don't show it if it isn't showing yet. ...

A nicer way is to make a custom class for the Toast like jitain sharma suggested in the comments.

OTHER TIPS

If you want that Toast should not remain on the screen when you move out of Activity then I would suggest you to use third party library Crouton

Try this way

in Fragment:

final Toast toast = Toast.makeText(getActivity(), "Test", Toast.LENGTH_SHORT);
            toast.show();

            Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                   @Override
                   public void run() {
                       toast.cancel(); 
                   }
            }, 500);

in Activity:

 final Toast toast = Toast.makeText(activity.this, "Test", Toast.LENGTH_SHORT);
            toast.show();

            Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                   @Override
                   public void run() {
                       toast.cancel(); 
                   }
            }, 500);

Use below code in your activity onDestory method:

toast.cancel();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top