I have a button in my activity. If I click on show Toast. But when I click again Toast show again. So in result when I click many times this Toast will appear for long time. When first disapear, next is showing and etc. How I can do when I click again on button, first toast will be hide.
Asked
Active
Viewed 3,646 times
3
-
1check [this](http://stackoverflow.com/questions/5295765/toast-issue-in-android/5295800#5295800) – silwar Apr 23 '12 at 10:42
-
how I can check if my toast is still on the screen? – edi233 Apr 23 '12 at 11:40
-
when u show toast on screen start timer which has same as duration given to toast if you are calling show toast again then check timer. if it is still running means toast is still there on screen – silwar Apr 23 '12 at 11:42
-
no need to use timers. if you want to dismiss previous toast, if showing, and display new one then simply take a gloabal instance of a Toast in your activity and make it null whenever you call cancel. and before calling cancel() check if this object is not null. – N-JOY Apr 23 '12 at 13:40
2 Answers
5
call cancel()
method to hide Toast if already showing.
Have a look at this API.
This can be simply called on Toast's object.
Toast toast = new Toast(context);
toast.setText("Text");
toast.show();//(call show() to display Toast)
toast.cancel();//(call cancel() to hide Toast).

N-JOY
- 10,344
- 7
- 51
- 69
-
When I tried to use the code above I got an error message. The solution was to use the static Method "Toast.makeText": **Toast.makeText(getApplicationContext(), "Text", 2000).show();** (2000 is the duration of 2 seconds) – Bruno Bieri Aug 28 '12 at 18:59
-
Throws a Runtime exception: **java.lang.RuntimeException: This Toast was not created with Toast.makeText()** – Abimbola Esuruoso Mar 14 '15 at 15:04
3
Add this code to your activity (global toast) and cancel it once you want to show a new text.
Toast myLovelyToastThatNeverDies;
public void onClick(View v) {
if(myLovelyToastThatNeverDies==null)
myLovelyToastThatNeverDies = new Toast(Activity.this);
else
myLovelyToastThatNeverDies.cancel();
myLovelyToastThatNeverDies.setText("my new text");
myLovelyToastThatNeverDies.setDuration(anAverageDuration);
myLovelyToastThatNeverDies.show();
}

Dan Hulme
- 14,779
- 3
- 46
- 95

Sherif elKhatib
- 45,786
- 16
- 89
- 106