How to cancel Toast created by another method on Android?

I have the following code:

private Toast movieRecordToast; private void displayNextMovie() { if (movieRecordToast != null) movieRecordToast.cancel(); // cancel previous Toast (if user changes movies too often) movieRecordToast = Toast.makeText(getApplicationContext(), "Next", Toast.LENGTH_SHORT); movieRecordToast.show(); private void displayPrevMovie() { if (movieRecordToast != null) movieRecordToast.cancel(); movieRecordToast = Toast.makeText(getApplicationContext(), "Prev", Toast.LENGTH_SHORT); movieRecordToast.show(); 

But if displayNextMovie is called quickly several times and then displayPrevMovie is displayPrevMovie , β€œNext” Toast is still displayed and only then β€œPrev” is displayed. Cancellation does not seem to work properly.

+9
android toast
Mar 31 '11 at 17:16
source share
3 answers

Instead of creating a new Toast every time you need new text, you can easily hold only one Toast and cancel the current Toast whenever you want. Before the next Toast is displayed, you can change the text using the Toast.setText() function.

Code example:

 private Toast mToastText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create the object once. mToastText = Toast.makeText(this, "", Toast.LENGTH_SHORT); } private void displayText(final String message) { mToastText.cancel(); mToastText.setText(message); mToastText.show(); } 
+28
Mar 31 '11 at 18:55
source share

I think there are many ways in which you can achieve the display of the next / previous information to the user. I would completely refuse toasts and update the TextView text with the name of the next / previous movie. This will fix your problem, and IMHO will improve the interface.

However, if your design requirements request toast notifications, try:

  private Toast nextMovieRecordToast; private Toast prevMovieRecordToast; private void displayNextMovie() { if (prevMovieRecordToast != null) prevMovieRecordToast.cancel(); // cancel previous Toast (if user changes movies too often) nextMovieRecordToast = Toast.makeText(getApplicationContext(), "Next", Toast.LENGTH_SHORT); nextMovieRecordToast.show();} private void displayPrevMovie() { if (nextMovieRecordToast != null) nextMovieRecordToast.cancel(); prevMovieRecordToast = Toast.makeText(getApplicationContext(), "Prev", Toast.LENGTH_SHORT); prevMovieRecordToast.show(); } 
0
Mar 31 '11 at 17:38
source share

Wroclai's solution is excellent! However, it pinches Toast when moving from a long toast to a short message and vice versa. Correct this, and not use the previous object, recreate it. Therefore, instead of this line:
mToastText.setText(message);
write: myToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
The animation also looks better :)

0
Feb 04 '15 at 20:28
source share



All Articles