0

In my application for Android the user has to tap a button and every time the button is tapped a toast appears saying "you have tapped n times", but if the user taps quickly several times the toasts are too slow and they appear one by one.

public void onClick(View v)
{
    n++;
    Toast.makeText(MainActivity.this, "You have tapped "+n+" times", Toast.LENGTH_SHORT).show();
}

Is there a way to "delete" all the old toasts in order to let appear only the last one?

Amit Upadhyay
  • 7,179
  • 4
  • 43
  • 57
maradev21
  • 576
  • 2
  • 6
  • 20
  • Keep a reference to your Toast object and call .cancel() to it. [Toast.cancel()](https://developer.android.com/reference/android/widget/Toast.html#cancel()) – ElegyD Feb 09 '17 at 16:05

2 Answers2

3

Instead of making a new Toast everytime, keep your instance and update the text

mToast.setText("newMessage");

Full example: How to change text in a Toast Notification dynamically while it's being displayed?

Community
  • 1
  • 1
Stefan
  • 2,098
  • 2
  • 18
  • 29
1

Keep a reference to the toast and dismiss it.

Toast toast; 

public void onClick(View v)
{
    if (toast != null) toast.dismiss()
    n++;
    toast =  Toast.makeText(MainActivity.this, "You have tapped "+n+" times", Toast.LENGTH_SHORT);
    toast.show()
}
fweigl
  • 21,278
  • 20
  • 114
  • 205